PHP equivalent for a python decorator?

前端 未结 5 598
夕颜
夕颜 2020-12-29 09:04

I want to be able to wrap a PHP function by another function, but leaving its original name/parameter list intact.

For instance:

function A() {
    p         


        
5条回答
  •  伪装坚强ぢ
    2020-12-29 09:39

    You can use Aspect Oriented Programming. But you need some framework that support AOP.

    For example Symfony. This is one of implementations of AOP for php https://github.com/goaop/goaop-symfony-bundle

    There is also the Nette Framework (I use this one)

    In principle it works like this: let's say you want to throw an exception if user is not logged in and tries to access some method.

    This is just "fictive" code to show how it works.

    You have some aspect method like this:

    /** @AroundMethod(annotataion="isUserLogged()") */
    public function checkUser(Method $method) {
        if ($this->user->isLogged()) {
            return $method->call();
        } else {
            throw new \Exception('User must be logged');
        }
    }
    

    And then you can use the annotation @isUserLogged in your services which will be probably registered in some DI container.

    /**
     * @isUserLogged()
     */
    public function changeUserInfo() {
    
    }
    

提交回复
热议问题