[英]How to Combine Two Methods Into One
我正在研究一個既包含事件又包含MVC PHP應用程序掛鈎的插件類。
如所想像的那樣,事件被設計為在狀態更改時被調用,主要是在模型中,因為數據是在那里更改的,其中一些還散布到控制器中,用於登錄,注銷等。
我希望大多數應用程序中的方法都可以使用鈎子,會有一些例外。
我已經建立了鈎子的存儲和注冊,然后將它們推入我的注冊表類,以便在整個應用程序中都可以使用它們。
鈎子的存儲方式如下:
Array
(
[admin_controller] => Array // type of hook
(
[0] => Array
(
[class] => \Admin\Controller\Tool\Test // class to hook
[method] => index // method to hook
[callback] => /Plugin/Test/Hooks/Controller/exampleHook // callback to run
[arguments] => Array // any arguments required
(
[heading_title] => Example Test Page
[item_title] => Item title
)
)
)
)
但是現在我不確定如何將兩種方法合而為一。 我不希望鈎子覆蓋原始方法,只需添加它即可。
我也不想去通過1700文件應用程序中的每種方法來監聽它:P
有沒有一種方法可以獲取給定方法的內容,並將其傳遞給匿名函數以將兩者構建為一個,還是應該反映出來?
使這項工作最佳的技術是什么?
對於任何感興趣的人,我都使用閉包將回調作為參數傳遞給現有方法。
$callable = false;
$hook_key = str_replace('\\', '', strtolower($prefix)) . '_controller';
if (array_key_exists($hook_key, $hooks)):
foreach($hooks[$hook_key] as $hook):
if ($hook['class'] === $class && $hook['method'] === $this->method):
$mthd = basename($hook['callback']);
$cls = rtrim(str_replace($mthd, '', $hook['callback']), '/');
$callback = array(
'class' => str_replace('/', '\\', $cls),
'method' => $mthd,
'args' => $hook['arguments']
);
$callable = function () use ($callback) {
$hook = new $callback['class'];
if (is_callable(array($hook, $callback['method']))):
return call_user_func_array(array($hook, $callback['method']), $callback['args']);
endif;
};
endif;
if ($callable):
$this->args[] = $callable();
endif;
endforeach;
endif;
唯一剩下的問題是,鈎子參數數組在執行時會丟失其鍵。
在上面的回調中轉儲func_get_args()
時,它會產生:
array (size=2)
0 => string 'Example Test Page' (length=17)
1 => string 'Item title' (length=10)
如果我將'args' => $hook['arguments']
包裝在數組'args' => array($hook['arguments'])
則將保留鍵,但是將嵌套該數組。
array (size=1)
0 =>
array (size=2)
'heading_title' => string 'Example Test Page' (length=17)
'item_title' => string 'Item title' (length=10)
任何想法將不勝感激。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.