6

Design question / PHP: I have a class with methods. I would like to call to an external function anytime when any of the methods within the class is called. I would like to make it generic so anytime I add another method, the flow works with this method too.

Simplified example:

<?php

function foo()
{
    return true;
}

class ABC {
    public function a()
    {
        echo 'a';
    }
    public function b()
    {
        echo 'b';
    }
}

?>

I need to call to foo() before a() or b() anytime are called.

How can I achieve this?

4
  • Any necessary for that. It seems to be like a constructor in a class Commented Mar 2, 2015 at 10:08
  • Use the decorator pattern with hooks to the __call and __callStatic to intercept any method call and execute your function before doing the real call. Commented Mar 2, 2015 at 10:11
  • @didierc can you please paste a sudo code here as it is not understandable for many people beginners like me. Commented Mar 2, 2015 at 10:24
  • @RaheelKhan I have no doubt you'll be able to figure it out by yourself with a little bit of time. Anyway, my answer is posted. Commented Mar 2, 2015 at 10:26

1 Answer 1

9

Protect your methods so they're not directly accessible from outside the class, then use the magic __call() method to control access to them, and execute them after calling your foo()

function foo()
{
    echo 'In pre-execute hook', PHP_EOL;
    return true;
}

class ABC {
    private function a()
    {
        echo 'a', PHP_EOL;
    }
    private function b($myarg)
    {
        echo $myarg, ' b', PHP_EOL;
    }

    public function __call($method, $args) {
        if(!method_exists($this, $method)) {
            throw new Exception("Method doesn't exist");
        }
        call_user_func('foo');
        call_user_func_array([$this, $method], $args);
    }
}

$test = new ABC();
$test->a();
$test->b('Hello');
$test->c();
Sign up to request clarification or add additional context in comments.

1 Comment

It does not work if ABC class is extended and ABC class uses parent class method. It gets to call_user_func_array and generates method not found an exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.