doubu1853 2013-08-12 11:57
浏览 68

Php Yii,如何注册由控制器提出的事件

What I want to do: Register a component to an event raised by a controller.

In my config main.php:

'preload' => array(MessageConsumer) // actually an impl class of interface

In my MessageConsumer impl

public function init() {
    Yii::app()->getController()->onMessageReceived = array($this, 'onMessageReceived');
}

Expected result: when the init method fires the consumer is registered to the current controller.

Actual result: there's no current controller yet. It seems the pre-load is performed before the webapplication does the controller magic.

So I tried something like:
In my MessageConsumer impl:

public function init() {
    $self = $this;
    Yii::app()->onBeginRequest(function() use ($self) {
        $controller = Yii::app()->getController();
        if($controller instanceof MessagingController) {
            Yii::app()->getController()->onMessageReceived = array($self, 'onMessageReceived');
        }
    });
}

Which doesn't work either because it seems the init() is called after the onBeginRequest() event is raised by the webapp.

Is there a way to register to events raised by a controller without explicitly linking the component to the controller class? Obviously I could register the listener in the constructor of the controller but I want to loosely couple the 2 components by using configuration.

Maybe there's some event like "onComponentLoaded" for which I could register? Since a Controller is a component I'd expect the Yii core to fire the event whenever there's a component loaded if there's such an event at all.

  • 写回答

1条回答 默认 最新

  • dongmi5015 2013-08-14 00:17
    关注

    I presume this is what you looking for, the onBeforeAction();

    <?php
    class YourController extends Controller
    {
        //this action is executed before any controller action
        protected function beforeAction($action)
        {
            //do stuff before controll action
            return true;
        }
    
        //the rest ofyour controller actions and stuff
        public function actionIndex(){
            //[...]
        }
    }
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程