PHP before action and after action

陌路散爱 提交于 2019-12-25 01:47:08

问题


I would like to know how can I do something similar with beforeAction() and afterAction() from Yii.

I need to have the same behavior in my PHP like those two functions from Yii and I don't know where to start from.

What I really need in my case is that every time a function executes, it has to reload some parameters and after the function executes it's code, it has to set them again.

The first action can be done in the constructor but the second one can only be done using a callback and this is not quite lovely.

I also need to implement this because the number of functions is about 30 and each one is doing something similar. Using this kind of behaviors I'll reduce the code size with about 70%.

function a1(){
  load();
  procA1();
  set();
}

function a2(){
  load();
  procA2();
  set();
}

function a3(){
  load();
  procA3();
  set();
}
and so on...

回答1:


Updated: Use call_user_func($function_name, (optional) $parametrs) + magic __call method. It is exactly the same as in Yii.

public function __call($name,$args) {
   if (method_exists($this,$name)) {
      $this->beforeAction();
      $ret =  call_user_func_array(array($this, $name), $args);
      $this->afterAction();
      return $ret;
   }
}

Now you can simple call $object->a3(). You can have function named a3 in the class, but add private modifier to it.



来源:https://stackoverflow.com/questions/20826311/php-before-action-and-after-action

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