Using Hooks

Hooks are used in many applications and frameworks. The special approach of Agile Toolkit is that hooks are defined "per-object". As an example, form will bind loadData() and submit() on API's hooks. This allows Form objects to execute code between initialization and rendering.

Hooks are typically used by controllers, add-ons. More hooks can be gradually added through hook() to standard classes. Here is example of a hook:

$obj->hook('myhook');

Calling this will actually execute all the code which was assigned here by addHook()

Using different callable types

There are several ways to specify a callable to an addHook():

$obj->addHook('myhook',function($o){ echo 'closure'; });

$obj->addHook('myhook',array($this'method')); // executes $this->method($obj);

$obj->addHook('myhook',array($this)); // shortcut for $this->myhook($obj);

Arguments to hooks

It's possible to pass arguments to a hooked functions:

$obj->addHook('myhook',function($o,$subj){ echo $subj; });

$obj->hook('myhook',array('hello world'));

Priority

By default all the hooks are added with priority=5. If you specify a lesser number to addHook() your hook will be executed before other hooks. Specifying value greater than 5 will leave your function to be executed after.

Hooks with same priority will be executed in the same order they have been added. To reverse this order use negative priority.

$this->addHook('myhook',function($o){ echo 'world'; },-1);
$this->addHook('myhook',function($o){ echo 'hello'; },-1);

$this->hook('myhook');

Returning values from hooks

Because there might be multiple handlers on a single hook, returning values will be stored in array:

$this->addHook('myhook',function($o){ return 'foo'; });
$this->addHook('myhook',function($o){ return 'bar'; });

var_dump ($this->hook('myhook')); // will show array('foo','bar');

If hooks are not defined, empty array will be returned. It's a quite popular construct, which uses a fall-back code in case hooks were not defined:

if(!$this->hook('myhook')){
  
// default handler
}

Breaking hook

In some cases you would want to stop any other hooks from being called. To do so, call $this->breakHook($return_value);. This method will raise exception which hook() will the intercept and retrieve return value

If hook is intercepted then return of hook() method is set to the first argument of breakHook();