PHP操作前和操作后 [英] PHP before action and after action

查看:80
本文介绍了PHP操作前和操作后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用Yii中的beforeAction()和afterAction()做类似的事情.

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

我需要在PHP中具有与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.

我还需要实现这一点,因为函数的数量约为30个,并且每个函数都在执行类似的操作.通过这种行为,我将代码大小减少了约70%.

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...

推荐答案

已更新: 使用call_user_func($function_name, (optional) $parametrs) +魔术__call方法.与Yii完全相同.

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;
   }
}

现在您可以简单地调用$object->a3().您可以在类中具有名为a3的函数,但要在其中添加private修饰符.

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

这篇关于PHP操作前和操作后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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