2016-07-14 77 views
0

我在ProductsController中有功能productsCount()。它給了我表中的記錄數量。如何在cakephp 3的不同視圖中從控制器調用函數?

public function productsCount() { 
     $productsAmount = $this->Products->find('all')->count(); 

     $this->set(compact('productsAmount')); 
     $this->set('_serialize', ['productsAmount']); 

    } 

我想調用這個函數來查看PageController。我想簡單地顯示ctp文件中的產品數量。

我該怎麼做?

回答

0

我認爲在PageController中找到產品數量會更有意義。因此,在PageController的視圖動作中添加諸如$productsAmount = $this->Page->Products->find('all')->count();之類的內容,並設置$productsAmount。如果「頁面」和「產品」不相關,那麼只要您爲「產品」包含use,就可以保持查找呼叫。

還檢查了這一點的型號命名約定:http://book.cakephp.org/3.0/en/intro/conventions.html#model-and-database-conventions

型號名稱應爲單數,所以改變產品到產品。你

-2

也可以定義static方法如下

public static function productsCount() { 
    return = $this->Products->find('all')->count(); 
} 

而在其他操作使用self::productsCount()

僅當您需要在控制器中計算多次時纔有用。否則你可以直接使用它如下:

$this->Products->find('all')->count(); 
+0

您不能在靜態函數中使用'$ this'。 –

2

可以使用view cell。無論控制器如何,這些控制器都可以被調用到任何視圖中。

創建src/View/Cell/productsCountCell.phpsrc/Template/Cell/ProductsCount/display.ctp

在你src/View/Cell/productsCountCell.php

namespace App\View\Cell; 

use Cake\View\Cell; 

class productsCountCell extends Cell 
{ 

    public function display() 
    { 
     $this->loadModel('Products'); 
     $productsAmount = $this->Products->find('all')->count(); 

     $this->set(compact('productsAmount')); 
     $this->set('_serialize', ['productsAmount']); 
    } 

} 

src/Template/Cell/ProductsCount/display.ctp攤開來一個模板,你怎麼想:

<div class="notification-icon"> 
    There are <?= $productsAmount ?> products. 
</div> 

現在,您可以撥打細胞到任何視圖像這樣:

$cell = $this->cell('productsCount'); 
相關問題