Kontakt - Datenschutz

Subversion

<?php
// Use the magic method __call to automatically execute methods before and after a method call
// for example to validate the state of on object before the data is stored in a database.

class Foo {
    private $callBefore = ['foo' => ['fooBefore']];
    private $callAfter  = ['foo' => ['fooAfter']];


    public function __construct() {
    }// __construct


    public function addCallBefore($call, $before) {
        $this->callBefore[$before][] = $call;
    }// addCallBefore


    public function __call($name, $arguments) {
        if(isset($this->callBefore[$name])) {
            foreach($this->callBefore[$name] as $call) {
                call_user_func_array([$this, $call], $arguments);
            }
        }

        call_user_func_array([$this, $name], $arguments);

        if(isset($this->callAfter[$name])) {
            foreach($this->callAfter[$name] as $call) {
                call_user_func_array([$this, $call], $arguments);
            }
        }
    }// __call


    private function fooBefore($val1, $val2) {
        echo "fooBefore: $val1, $val2\n";
    }// fooBefore


    private function foo($val1, $val2) {
        echo "foo: $val1, $val2\n";
    }// foo


    private function fooAfter($val1, $val2) {
        echo "fooAfter: $val1, $val2\n";
    }// fooAfter


    private function validate() {
        echo "validate\n";
    }// validate


    public function callFooFromInside() {
        // Only foo() because foo() is now visible and __call is not used
        $this->foo(1, 2);
    }// callFooFromInside
}// Foo


$foo = new Foo();
$foo->foo(1, 2);

echo "---------- add validate\n";
$foo->addCallBefore('validate', 'foo');
$foo->foo(1, 2);

echo "---------- callFooFromInside\n";
$foo->callFooFromInside();
?>