如何在cakephp 3的不同视图中从控制器调用函数?

问题描述:

我在ProductsController中有功能productsCount()。它给了我表中的记录数量。如何在cakephp 3的不同视图中从控制器调用函数?

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

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

    } 

我想调用这个函数来查看PageController。我想简单地显示ctp文件中的产品数量。

我该怎么做?

我认为在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

型号名称应为单数,所以改变产品到产品。你

也可以定义static方法如下

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

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

仅当您需要在控制器中计算多次时才有用。否则你可以直接使用它如下:

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

您不能在静态函数中使用'$ this'。 –

你不能从视图页面调用控制器方法。您可以创建帮助程序,您可以从查看页面调用该帮助程序。

在这里,你会得到一个适当的文件创建helpers- http://book.cakephp.org/3.0/en/views/helpers.html#creating-helpers

可以使用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');