Skip to content

Commit

Permalink
hook $this by default (#126)
Browse files Browse the repository at this point in the history
* assign $this as default value for fx

* update exception info

* update docs
  • Loading branch information
georgehristov authored Feb 25, 2020
1 parent cdb8e0b commit 3e956a3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
8 changes: 5 additions & 3 deletions docs/hook.rst
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,23 @@ You can register multiple call-backs to be executed for the requested `spot`::
Adding callbacks
================

.. php:method:: onHook($spot, $callback, $args = null, $priority = 5)
.. php:method:: onHook($spot, $fx = null, $args = null, $priority = 5)
Register a call-back method. Calling several times will register multiple
callbacks which will be execute in the order that they were added.

Short way to describe callback method
=====================================

There is a concise syntax for using $callback by specifying object only.
There is a concise syntax for using $fx by specifying object only.
In case $fx is omitted then $this object is used as $fx.

In this case a method with same name as $spot will be used as callback::

function init() {
parent::init();

$this->onHook('beforeUpdate', $this);
$this->onHook('beforeUpdate');
}

function beforeUpdate($obj){
Expand Down
11 changes: 6 additions & 5 deletions src/HookTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,9 @@ public function addHook($hookSpot, $fx, $args = null, $priority = null)
*
* @return $this
*/
public function onHook($hookSpot, $fx, $args = null, $priority = null)
public function onHook($hookSpot, $fx = null, $args = null, $priority = null)
{
$fx = $fx ?: $this;

// Set defaults
if (is_null($args)) {
Expand Down Expand Up @@ -70,22 +71,22 @@ public function onHook($hookSpot, $fx, $args = null, $priority = null)
if (!$fx->hasMethod($hookSpot)) {
throw new Exception([
'$fx should be a valid callback',
'callable' => $fx,
'fx' => $fx,
]);
}
} else {
if (!method_exists($fx, $hookSpot)) {
throw new Exception([
'$callable should be a valid callback',
'callable' => $fx,
'$fx should be a valid callback',
'fx' => $fx,
]);
}
}
$fx = [$fx, $hookSpot];
} else {
throw new Exception([
'$fx should be a valid callback',
'callable' => $fx,
'fx' => $fx,
]);
}
}
Expand Down

0 comments on commit 3e956a3

Please sign in to comment.