From 3e956a3f8367108b1f126a4ca9b8e86c831a036e Mon Sep 17 00:00:00 2001 From: Georgi Hristov Date: Tue, 25 Feb 2020 16:33:25 +0100 Subject: [PATCH] hook $this by default (#126) * assign $this as default value for fx * update exception info * update docs --- docs/hook.rst | 8 +++++--- src/HookTrait.php | 11 ++++++----- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/hook.rst b/docs/hook.rst index 751b333b..f1794ab6 100644 --- a/docs/hook.rst +++ b/docs/hook.rst @@ -35,7 +35,7 @@ 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. @@ -43,13 +43,15 @@ 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){ diff --git a/src/HookTrait.php b/src/HookTrait.php index 3840bf58..cff5d993 100644 --- a/src/HookTrait.php +++ b/src/HookTrait.php @@ -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)) { @@ -70,14 +71,14 @@ 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, ]); } } @@ -85,7 +86,7 @@ public function onHook($hookSpot, $fx, $args = null, $priority = null) } else { throw new Exception([ '$fx should be a valid callback', - 'callable' => $fx, + 'fx' => $fx, ]); } }