Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a function before method call

Tags:

php

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?

like image 801
daqeraty Avatar asked Mar 02 '15 10:03

daqeraty


1 Answers

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();
like image 137
Mark Baker Avatar answered Sep 30 '22 01:09

Mark Baker