【问题标题】:Cakephp 3 : How loadModel function defines globally?Cakephp 3:loadModel 函数如何全局定义?
【发布时间】:2015-10-08 07:04:06
【问题描述】:

我是 cakephp3 的新手。我阅读了http://book.cakephp.org/3.0/ 并开始使用 cakephp3 开发小型应用程序。 我正在使用 UserMastersController,我想从 person_masters 表中保存和获取数据。为此,每次我使用 loadModel() 或 TabelRegistry::get();每个函数中的方法。

$this->loadModel('PersonMasters');

那么,如何在cakephp3中全局定义其他模型,所以我不应该在每个函数中每次都定义?

【问题讨论】:

  • 你想为每个控制器加载这个模型吗?
  • 不是为每个控制器..但我想为一个特定的控制器全局定义模型...因为在我的 UserMasterController 中有不同的函数使用 person_masters 数据库表..所以每次我写这一行:$this->loadModel('PersonMasters');在每个函数中..那么我如何全局定义?
  • 您在哪里尝试过此代码?能否提供您的查找方法?

标签: cakephp orm model cakephp-3.0


【解决方案1】:

使用 beforeFilter

我正在使用 loadModel() 或 TabelRegistry::get();每个函数中的方法。

最简单的解决方案是在相关控制器中define the beforeFilter method

public function beforeFilter(Event $event)
{
    $this->loadModel('PersonMasters');
    parent::beforeFilter($event);
}

public function example()
{
    $this->PersonMasters->find(); // no error
}

如果您愿意,可以改为更改默认表类的名称,即is set automatically to the name of the controller class - if it isn't already set。这就是“FoosController 将使用 Foos 表类”的约定的实现方式。 IE。这也可以:

public function beforeFilter(Event $event)
{
    $this->modelClass = 'PersonMasters';
    parent::beforeFilter($event);
}

public function example()
{
    $this->PersonMasters->find(); // no error
}

虽然这对于代码的未来读者(例如,你,明年,下周 - 或明天 =)来说更间接并且可能更令人困惑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 2015-05-07
    • 2011-05-26
    • 2018-05-24
    • 1970-01-01
    • 2012-09-28
    相关资源
    最近更新 更多