use controller method from model class in cakephp

此生再无相见时 提交于 2020-01-15 07:37:24

问题


In my cakephp project, I use afterSave() method of a model class. In this method, I want to call another method that is located in app_controller file.

class MyModel extends AppModel {

        var $name = 'MyModel';

        function afterSave($created) {

            $this->MyController->updateData();          
        }

}

Here updateData() is located in app_controller file, which is extended by MyController controller.

The above code does not work, so how can i actually call updateData() in this case..

Please guide.

Thanks


回答1:


This is strongly NOT recommended but it can be done anyway... You should try as deizel says and move that method to AppModel or any other particular model...

you may use this function

App::import() check the book here to see how to use it

in your example:

class MyModel extends AppModel {

        var $name = 'MyModel';

        function afterSave($created) {
            App::import('Controller', 'My');
            $something = new MyController;
            $something->updateData();          
        }

}

This is the correct way to load a class inside another place where it shouldn't be... Still you may use include or required and create an instance of the class since this is php.



来源:https://stackoverflow.com/questions/7598675/use-controller-method-from-model-class-in-cakephp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!