Cakephp 3回调,所有模型的行为 [英] Cakephp 3 callbacks, behaviors for all models

查看:91
本文介绍了Cakephp 3回调,所有模型的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始阅读cakephp 3文档(我一直在使用cake 2.x进行开发),并且希望将某些网站从2.x迁移到3。在我的 AppModel 我有一些回调,尤其是 beforeFind beforeSave ,其中包含一些有关几乎所有表的逻辑在数据库中。

I just started reading cakephp 3 docs (I have been developing with cake 2.x for some time) and want to migrate some website from 2.x to 3. In cake 2 in my AppModel I have some callbacks, particularly beforeFind and beforeSave, that contain some logic concerning almost all tables in a database.

现在蛋糕3中没有 AppModel ,我该怎么做?我能想到的最好的方法是将该代码放入某些行为的回调中,但是我有30个模型,是否应该一一加载所有模型中的行为?

Now in cake 3 there is no AppModel, how do I get the same thing done ? The best I can think of is to put that code in some behavior's callbacks, but I have like 30 models, should I load the behavior in all models one by one ?

谢谢

推荐答案

使用事件监听器监听事件 Model.beforeSave Model.beforeFind Model.initialize 并在此应用您想要执行的任何操作。 阅读有关事件的章节表回调的文档

Use an event listener that listens to the events Model.beforeSave, Model.beforeFind and Model.initialize and apply whatever you want to do there. 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
    }
}

并将其附加到 全局 事件管理器。现在它将监听 all 表对象的回调。

And attach it to the global event manager. It will now listen to the callbacks of all table object.

这篇关于Cakephp 3回调,所有模型的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆