Written on January 21, 2017
Feature available on Github from January 21, 2017

One of the latest features of the framework is the possibility to use “hooks” to provide a way for a script to let plugins alter its execution. For those familiar with WordPress, it’s basically the same functionality as WordPress hooks/actions.

This feature can extend a class’ functionalities either transparently and/or collaboratively. Transparently means the decorated class is given new methods (the usual decorator pattern), collaboratively means the decorated class explicitly informs its decorators that a specific point has been reached (the Wordpress hook approach).

In the following example, we’ll study a “decorated” class, and a “decorator” class, the later providing the former with a “transparent()” method and “collaborate()” method.

class decorated
{
    function do_something()
    {
        echo "Starting...";
        $what = $this->inform('collaborate', $some_data);
        echo "Someone said ".$what;
        echo "End";
    }
}
class decorator extends PHPDS_dependant
{
    function transparent()
    {
        echo "I'm transparent!";
    }
    function collaborate($params = null, $result = null)
    {
        echo "I'm playing nice";
        return 'Hello!';
    }
}
$this->classes->registerClass('decorator', '§decorated', '');

To register a decorator, simply prefix its target with ‘§’.

After registration, any new “decorated” instance will have two new methods, “transparent()” and “collaborate()”, both would execute in the context of a new “decorator” instance, which “transparent” field is set to the decorated instance:

$decorated->transparent(); // I'm transparent!
$decorated->do_something();
Starting...
I'm playing nice
Someone said Hello!
End

Of course, several decorators can be hooked to the same decorated. You can register in code like in this example, or in your plugin’s plugin.config.xml. The advantage of the second method is that the decorator class file is loaded only when a decorated object is instantiated, making it faster and more memory efficient.

Réaction

Était-ce utile?

Oui Non
Vous avez indiqué que ce sujet ne vous a pas été utile ...
Pouvez-vous SVP laisser un commentaire nous disant pourquoi? Merci!
Merci pour vos commentaires.

Laissez votre avis sur ce sujet.

Valider