CakePHP如何创建函数并从视图调用它们


CakePHP how to create functions and call them from view

如何创建可以在视图中调用的函数(如在index.ctp中)?

我刚刚在我的一个控制器中写了一个函数:

public function getName($id) {
    $name = $users
      ->find()
      ->where(['id' => $id ])
      ->first()
      ->username;
    return $name;
}

函数应该根据作为参数传递的$id返回用户名。我只是想知道如何从我的视图中调用函数。我得到这个错误:

"Error: Call to undefined function getName()"

对于此类工作,您可以使用cakePHP Cell

//src/View/Cell/UserCell.php
namespace App'View'Cell;
use Cake'View'Cell;
class UserCell extends Cell{
    public function getName($id) {
        $users = TableRegistry::get('Users');// or may use $this->loadModel('Users');
        $name = $users->find()->where(['id' => $id ])->first()->username;
    return $name; 
    }
}

现在你可以从视图

调用
echo $this->cell('User::getName', [$id]);

官方文档

你可以这样做,但这是违反mvc模型的,无论如何都不推荐。

Namespace'ControllerName::getName(1)

你真的应该考虑看看CakePHP手册,了解如何设置变量从控制器查看http://book.cakephp.org/3.0/en/views.html#setting-view-variables