Cakephp 3 回调,所有模型的行为
Cakephp 3 callbacks, behaviors for all models
我刚开始阅读 cakephp 3 文档(我用 cake 2.x 开发了一段时间)并想将一些网站从 2.x 迁移到 3。在我的 [= 中的 cake 2 10=] 我有一些回调,特别是 beforeFind
和 beforeSave
,它们包含一些关于数据库中几乎所有表的逻辑。
现在蛋糕 3 中没有 AppModel
,我该如何完成同样的事情?我能想到的最好的办法是将该代码放在某些行为的回调中,但我有大约 30 个模型,我是否应该将行为一一加载到所有模型中?
谢谢
使用监听事件 Model.beforeSave
、Model.beforeFind
和 Model.initialize
的事件监听器,并在那里应用您想做的任何事情。 Read the chapter about events and the documentation for table callbacks.
use Cake\Event\EventListenerInterface;
use Cake\Event\Event;
class SomeListener implements EventListenerInterface
{
public function implementedEvents()
{
return [
'Model.beforeFind' => 'beforeFind',
];
}
public function beforeFind(Event $event, Query $query, ArrayObject $options, boolean $primary)
{
// Your code here
}
}
并将其附加到 the global 事件管理器。它现在将监听 all table object.
的回调
您还可以在 src/Model/Table 文件夹:
中创建应用程序Table
namespace App\Model\Table;
use Cake\ORM\Table;
class AppTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->addBehavior('myBehavior');
$this->addBehavior('myBehavior2');
$this->addBehavior('myBehavior3');
}
}
然后通过 AppTable:
扩展您的 Table class
namespace App\Model\Table;
use App\Model\Table\AppTable;
class ArticlesTable extends AppTable
{
}
我刚开始阅读 cakephp 3 文档(我用 cake 2.x 开发了一段时间)并想将一些网站从 2.x 迁移到 3。在我的 [= 中的 cake 2 10=] 我有一些回调,特别是 beforeFind
和 beforeSave
,它们包含一些关于数据库中几乎所有表的逻辑。
现在蛋糕 3 中没有 AppModel
,我该如何完成同样的事情?我能想到的最好的办法是将该代码放在某些行为的回调中,但我有大约 30 个模型,我是否应该将行为一一加载到所有模型中?
谢谢
使用监听事件 Model.beforeSave
、Model.beforeFind
和 Model.initialize
的事件监听器,并在那里应用您想做的任何事情。 Read the chapter about events and the documentation for table callbacks.
use Cake\Event\EventListenerInterface;
use Cake\Event\Event;
class SomeListener implements EventListenerInterface
{
public function implementedEvents()
{
return [
'Model.beforeFind' => 'beforeFind',
];
}
public function beforeFind(Event $event, Query $query, ArrayObject $options, boolean $primary)
{
// Your code here
}
}
并将其附加到 the global 事件管理器。它现在将监听 all table object.
的回调您还可以在 src/Model/Table 文件夹:
中创建应用程序Tablenamespace App\Model\Table;
use Cake\ORM\Table;
class AppTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->addBehavior('myBehavior');
$this->addBehavior('myBehavior2');
$this->addBehavior('myBehavior3');
}
}
然后通过 AppTable:
扩展您的 Table classnamespace App\Model\Table;
use App\Model\Table\AppTable;
class ArticlesTable extends AppTable
{
}