How to auto call function in php for every other function call

前端 未结 8 1930
夕颜
夕颜 2020-11-29 02:48
Class test{
    function test1()
    {
        echo \'inside test1\';
    }

    function test2()
    {
        echo \'test2\';
    }

    function test3()
    {
            


        
相关标签:
8条回答
  • 2020-11-29 03:04

    Your best bet is the magic method __call, see below for example:

    <?php
    
    class test {
        function __construct(){}
    
        private function test1(){
            echo "In test1", PHP_EOL;
        }
        private function test2(){
            echo "test2", PHP_EOL;
        }
        protected function test3(){
            return "test3" . PHP_EOL;
        }
        public function __call($method,$arguments) {
            if(method_exists($this, $method)) {
                $this->test1();
                return call_user_func_array(array($this,$method),$arguments);
            }
        }
    }
    
    $a = new test;
    $a->test2();
    echo $a->test3();
    /*
    * Output:
    * In test1
    * test2
    * In test1
    * test3
    */
    

    Please notice that test2 and test3 are not visible in the context where they are called due to protected and private. If the methods are public the above example will fail.

    test1 does not have to be declared private.

    ideone.com example can be found here

    Updated: Add link to ideone, add example with return value.

    0 讨论(0)
  • 2020-11-29 03:04

    Perhaps the best way so far is to create your own method caller and wrap around whatever you need before and after the method:

    class MyClass {
    
        public function callMethod()
        {
            $args = func_get_args();
    
            if (count($args) == 0) {
                echo __FUNCTION__ . ': No method specified!' . PHP_EOL . PHP_EOL;;
            } else {
                $method = array_shift($args); // first argument is the method name and we won't need to pass it further
                if (method_exists($this, $method)) {
                    echo __FUNCTION__ . ': I will execute this line and then call ' . __CLASS__ . '->' . $method . '()' . PHP_EOL;
                    call_user_func_array([$this, $method], $args);
                    echo __FUNCTION__ . ": I'm done with " . __CLASS__ . '->' . $method . '() and now I execute this line ' . PHP_EOL . PHP_EOL;
                } else
                    echo __FUNCTION__ . ': Method ' . __CLASS__ . '->' . $method . '() does not exist' . PHP_EOL . PHP_EOL;
            }
        }
    
        public function functionAA()
        {
            echo __FUNCTION__ . ": I've been called" . PHP_EOL;
        }
    
        public function functionBB($a, $b, $c)
        {
            echo __FUNCTION__ . ": I've been called with these arguments (" . $a . ', ' . $b . ', ' . $c . ')' . PHP_EOL;
        }
    }
    
    $myClass = new MyClass();
    
    $myClass->callMethod('functionAA');
    $myClass->callMethod('functionBB', 1, 2, 3);
    $myClass->callMethod('functionCC');
    $myClass->callMethod();
    

    And here's the output:

    callMethod: I will execute this line and then call MyClass->functionAA()
    functionAA: I've been called
    callMethod: I'm done with MyClass->functionAA() and now I execute this line 
    
    callMethod: I will execute this line and then call MyClass->functionBB()
    functionBB: I've been called with these arguments (1, 2, 3)
    callMethod: I'm done with MyClass->functionBB() and now I execute this line 
    
    callMethod: Method MyClass->functionCC() does not exist
    
    callMethod: No method specified!
    

    You can even go further and create a whitelist of methods but I leave it like this for the sake of a more simple example.

    You will no longer be forced to make the methods private and use them via __call(). I'm assuming that there might be situations where you will want to call the methods without the wrapper or you would like your IDE to still autocomplete the methods which will most probably not happen if you declare the methods as private.

    0 讨论(0)
  • 2020-11-29 03:13

    Maybe it is a little bit outdated but here come my 2 cents...

    I don't think that giving access to private methods via __call() is a good idea. If you have a method that you really don't want to be called outside of your object you have no way to avoid it happening.

    I think that one more elegant solution should be creating some kind of universal proxy/decorator and using __call() inside it. Let me show how:

    class Proxy
    {
        private $proxifiedClass;
    
        function __construct($proxifiedClass)
        {
            $this->proxifiedClass = $proxifiedClass;
        }
    
        public function __call($methodName, $arguments)
        {
    
            if (is_callable(
                    array($this->proxifiedClass, $methodName)))
            {
                doSomethingBeforeCall();
    
                call_user_func(array($this->proxifiedClass, $methodName), $arguments);
    
                doSomethingAfterCall();
            }
            else
            {
                $class = get_class($this->proxifiedClass);
                throw new \BadMethodCallException("No callable method $methodName at $class class");
            }
        }
    
        private function doSomethingBeforeCall()
        {
            echo 'Before call';
            //code here
        }
    
        private function doSomethingAfterCall()
        {
            echo 'After call';
            //code here
        }
    }
    

    Now a simply test class:

    class Test
    {
        public function methodOne()
        {
            echo 'Method one';
        }
    
        public function methodTwo()
        {
            echo 'Method two';
        }
    
        private function methodThree()
        {
            echo 'Method three';
        }
    
    }
    

    And all you need to do now is:

    $obj = new Proxy(new Test());
    
    $obj->methodOne();
    $obj->methodTwo();
    $obj->methodThree(); // This will fail, methodThree is private
    

    Advantages:

    1)You just need one proxy class and it will work with all your objects. 2)You won't disrespect accessibility rules. 3)You don't need to change the proxified objects.

    Disadvantage: You will lose the inferface/contract after wrapping the original object. If you use Type hinting with frequence maybe it is a problem.

    0 讨论(0)
  • 2020-11-29 03:13

    If you are really, really brave, you can make it with runkit extension. (http://www.php.net/manual/en/book.runkit.php). You can play with runkit_method_redefine (you can need Reflection also to retrieve method definition) or maybe combination runkit_method_rename (old function) / runkit_method_add (new function which wraps calls to your test1 function and an old function )

    0 讨论(0)
  • 2020-11-29 03:18

    The only way to do this is using the magic __call. You need to make all methods private so they are not accessable from the outside. Then define the __call method to handle the method calls. In __call you then can execute whatever function you want before calling the function that was intentionally called.

    0 讨论(0)
  • 2020-11-29 03:20

    All previous attempts are basically flawed because of http://ocramius.github.io/presentations/proxy-pattern-in-php/#/71

    Here's the simple example, taken from my slides:

    class BankAccount { /* ... */ }
    

    And here's our "poor" interceptor logic:

    class PoorProxy {
        public function __construct($wrapped) {
            $this->wrapped = $wrapped;
        }
    
        public function __call($method, $args) {
            return call_user_func_array(
                $this->wrapped,
                $args
            );
        }
    }
    

    Now if we have the following method to be called:

    function pay(BankAccount $account) { /* ... */ }
    

    Then this won't work:

    $account = new PoorProxy(new BankAccount());
    
    pay($account); // KABOOM!
    

    This applies to all solutions that suggest implementing a "proxy".

    Solutions suggesting explicit usage of other methods that then call your internal API are flawed, because they force you to change your public API to change an internal behavior, and they reduce type safety.

    The solution provided by Kristoffer doesn't account for public methods, which is also a problem, as you can't rewrite your API to make it all private or protected.

    Here is a solution that does solve this problem partially:

    class BankAccountProxy extends BankAccount {
        public function __construct($wrapped) {
            $this->wrapped = $wrapped;
        }
    
        public function doThings() { // inherited public method
            $this->doOtherThingsOnMethodCall();
    
            return $this->wrapped->doThings();
        }
    
        private function doOtherThingsOnMethodCall() { /**/ }
    }
    

    Here is how you use it:

    $account = new BankAccountProxy(new BankAccount());
    
    pay($account); // WORKS!
    

    This is a type-safe, clean solution, but it involves a lot of coding, so please take it only as an example.

    Writing this boilerplate code is NOT fun, so you may want to use different approaches.

    To give you an idea of how complicated this category of problems is, I can just tell you that I wrote an entire library to solve them, and some smarter, wiser, older people even went and invented an entirely different paradigm, called "Aspect Oriented Programming" (AOP).

    Therefore I suggest you to look into these 3 solutions that I think may be able to solve your problem in a much cleaner way:

    • Use ProxyManager's "access interceptor", which is basically a proxy type that allows you to run a closure when other methods are called (example). Here is an example on how to proxy ALL calls to an $object's public API:

      use ProxyManager\Factory\AccessInterceptorValueHolderFactory;
      
      function build_wrapper($object, callable $callOnMethod) {
          return (new AccessInterceptorValueHolderFactory)
              ->createProxy(
                  $object,
                  array_map(
                      function () use ($callOnMethod) {
                          return $callOnMethod;
                      },
                      (new ReflectionClass($object))
                          ->getMethods(ReflectionMethod::IS_PUBLIC)
                  )
              ); 
      }
      

      then just use build_wrapper as you like.

    • Use GO-AOP-PHP, which is an actual AOP library, completely written in PHP, but will apply this sort of logic to ALL instances of classes for which you define point cuts. This may or may not be what you want, and if your $callOnMethod should be applied only for particular instances, then AOP is not what you are looking for.

    • Use the PHP AOP Extension, which I don't believe to be a good solution, mainly because GO-AOP-PHP solves this problem in a more elegant/debuggable way, and because extensions in PHP are inherently a mess (that is to be attributed to PHP internals, not to the extension developers). Additionally, by using an extension, you are making your application as un-portable as possible (try convincing a sysadmin to install a compiled version of PHP, if you dare), and you can't use your app on cool new engines such as HHVM.

    0 讨论(0)
提交回复
热议问题