简体   繁体   English

PHP在行动之前和行动之后

[英]PHP before action and after action

I would like to know how can I do something similar with beforeAction() and afterAction() from Yii. 我想知道如何使用Yii的beforeAction()和afterAction()做类似的事情。

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. 我需要在PHP中使用与Yii中的两个函数相同的行为,我不知道从哪里开始。

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. 我还需要实现这个,因为函数的数量大约是30,每个函数都在做类似的事情。 Using this kind of behaviors I'll reduce the code size with about 70%. 使用这种行为,我将减少约70%的代码大小。

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

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

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

Updated: Use call_user_func($function_name, (optional) $parametrs) + magic __call method. 更新:使用call_user_func($function_name, (optional) $parametrs) + magic __call方法。 It is exactly the same as in Yii. 它和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() . 现在你可以简单地调用$object->a3() You can have function named a3 in the class, but add private modifier to it. 您可以在类中使用名为a3函数,但是为其添加private修饰符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM