我已经尝试过谷歌如何做到这一点,但我仍然无法弄明白。如何在PHP中创建一个简单的钩子?这是我到目前为止所尝试的:
wrapper.php (应用程序从这里开始)
<?php require 'core.php'; ?>
<?php require 'view.php'; ?>
core.php中
<?php
$hooks['hook_head'] = array();
//supposed to insert action in $hooks
function addHook($hookName, $funct){
global $hooks;
array_push($hooks[$hookName], $funct);
}
//supposed to execute specific hook
function executeHook($hookname){
global $hooks;
foreach($hooks[$hookname] as $funct){
call_user_func( $funct );
}
}
//supposed to execute action in $hooks when array key = hook_head
function hook_head(){
global $hooks;
if (array_key_exists('hook_head', $hooks)) {
executeHook( 'hook_head' );
}
}
//supposed to execute action in $hooks when array key == hook_footer
function hook_footer(){
global $hooks;
if (array_key_exists('hook_footer', $hooks)) {
executeHook( 'hook_footer' );
}
}
?>
view.php
<!DOCTYPE HTML>
<html>
<head>
<?php hook_head(); ?>
</head>
<body>
<hr />
<?php
//add action to hook start here
$test = function(){ echo "test succeds"; };
addHook('hook_head', $test);
?>
<?php hook_footer(); ?>
</body>
</html>
如果我在调用$hooks['hook_head']
之前在hook_head()
中插入操作,则代码可以正常工作。我实际上想要做的是在调用hook_head()
之后插入动作。我该怎么做呢?
答案 0 :(得分:2)
将addHook
来电移至hook_head
来电之前(最好是文件的开头)。
我注意到你“想要在调用hook_head()之后开始编码(在钩头中插入动作)”,但这非常麻烦。它看起来像那样:
hook_head()
以在输出中插入某种令牌。ob_get_clean()
以获取页面的输出缓冲区。ob_get_clean()
以获取挂钩的输出缓冲区。