Jump to content

A hook system question


ds111

Recommended Posts

Hello!

 

I have the following code, for example:

 

 

class Controller_test extends controller_template
{

           function action_index()
{
            $this->execute_hooks("action_index");

}

}

My execute_hooks function is this:

 


	if ( isset ( $this->hooks[$where] ) )
	{
		if (is_array($this->hooks[$where]))
		{
		    foreach($this->hooks[$where] as $key => $value)
		    {

		        $file        = $value['file'];
		        $function	 = $value['function'];

				require ( $file );

				$function()
		    }
		}
	}

This works correctly, however...I want something a bit more...

 

I want it to literally **add code to the function**

 

See the require( $file ); line?

Here's an example of a file:

 

 

<?php

function test()
{

    echo "Hi!";
}

?>

it calls the test() function, and echos "hi" in the correct place...

 

But what If I want to use some class-specific variable? It doesn't work.

 

I tried to literally read the file contents then return it to the execute_hooks() call, but that doesn't work.

 

So basically I want to turn this:

 

<?php
$this->execute_hooks("test");
?>

to this:

 

 

<?php
echo "hi!";

?>

How do i do it?

Link to comment
https://forums.phpfreaks.com/topic/186059-a-hook-system-question/
Share on other sites

Just a thought, would ya need an empty function set first?

$function_code=null

 

than add the extra code to the function

$function_code.='echo "hello";';

 

than just continue adding more code as neccessary.

$function_code.='echo " world";';

 

than just create an anonymous function,

$func=create_function('',$a);

 

now the anonymous function can be called anytime with

$func();

 

but if ya want to, I suppose ya can bypass the creation of functions entirely, and use eval instead if you want an immediate return

In order to access object variables you need to pass the object reference ($this) to your function/object.

 

protected function _executeHooks($identifier) {
    if ($hooks = $this->_getRegisteredHooks($identifier) && $hooks->count()) {
        foreach ($hooks as $hook) {
            try {
                $this->_executeHook($hook);
            } catch(Exception $e) {/* In case an invalid hook would make it to the hooks ArrayObject */}
        }
    }
}

protected function _executeHook(Hook $hook) {
    $hook->execut($this);
}

protected function _getRegisteredHooks($identifier) {
    return $this->_hooks->offsetExists($identifier)
        ? $this->_hooks->offsetGet($identifier) : new ArrayObject(/* NullObject */);
}

 

This is ofcourse just an example and may differ depening on your OO design

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.