【问题标题】:PHP - Call function at each method callPHP - 在每次方法调用时调用函数
【发布时间】:2020-11-01 01:29:05
【问题描述】:

我有几个类和几种方法。 我想在每个方法调用中执行一个函数,而在每个方法中没有相应的调用。

有没有办法自动化这个?类似于方法侦听器的东西?

【问题讨论】:

  • 你能提供一些示例代码并解释你为什么想要这种行为吗?据我所知,没有办法实现您所描述的这种行为,但也许我可以在了解用例时提出解决方案。
  • 每个classconstructor中都可以调用function
  • 我会检查每种方法的权限。我的访问控制基于每种方法。方法在配置文件中,配置文件在组中,组分配给用户...
  • 我认为您所描述的是某种中间件。在 Laravel 中,您不会检查方法的权限,而是检查路线。并且路由通常“耦合”到控制器方法。如果不想使用 Laravel,可以使用支持中间件的路由器库。
  • @Michael:感谢您的提示,但我正在编写自己的框架 :-)

标签: php class methods


【解决方案1】:

你可以声明你所有的方法private并像这样使用神奇的__call方法。

<?php

class MyClass
{
    private function doSomething($param1, $param2){ //your previously public method
       echo "do ".$param1." ".$param2;
    }
    private function doSomethingForbidden($param1, $param2){ //your previously public method
       echo "doSomethingForbidden";
    } 

    private function verifyPermission($methodName){
       return in_array($methodName, [
          "doSomething"
       ]);
    }

    public function __call($name, $arguments)
    {
        if($this->verifyPermission($name)){
          return call_user_func_array(array($this, $name), $arguments);
        }else{
          throw new \Exception("You can't do that !");
        }
    }
}

$nc = new MyClass();
$nc->doSomething("pet", "the dog");
//do pet the dog
$nc->doSomethingForbidden("feed", "the birds");
//Fatal error:  Uncaught Exception: You can't do that !

当方法是私有的或不存在时,PHP 会自动将调用路由到 __call 方法(如果存在)。从那里,你可以做你想做的事(检查权限,记录事情等),因为你现在“在”你的班级,你可以使用 call_user_func_array 和原始参数自己调用你的私有方法。

您可以通过阅读魔术方法文档了解更多信息https://www.php.net/manual/en/language.oop5.overloading.php#object.call

【讨论】:

  • 我经常使用它来记录日志。另一个神奇的方法也非常有用(比如强制转换、抛出有意义的异常等)
  • @MarcWampfler(如果它解决了您的问题,请不要忘记将答案标记为好!)
猜你喜欢
  • 2022-06-23
  • 1970-01-01
  • 2012-02-17
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多