Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hook $this by default #126

Merged
merged 3 commits into from
Feb 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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