Reputation: 99
I already tried to Google how to do this, but I still can't figure it out. How do I create a simple hook inside PHP? Here is what I've tried so far:
wrapper.php (application starts here)
<?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>
The code works fine if I insert an action inside $hooks['hook_head']
, before I call hook_head()
. What I actually am trying to do though, is insert the action after I called hook_head()
. How do I do this?
Upvotes: 2
Views: 4357
Reputation: 31655
Move the addHook
call to before the hook_head
call (preferably to the beginning of the file).
I did notice that you "want to start coding (insert action in hook head) after it call hook_head()", but that's very cumbersome. It would look something like that:
hook_head()
to insert some kind of token into the output.ob_get_clean()
to get the output buffer of the page.ob_get_clean()
again to get the output buffer of the hook.As I said: cumbersome. I strongly advice against it. I only mentioned it because you asked specifically. It contradicts the intuitive control flow of
Upvotes: 3