I have an idea for the event system I'm developing for my custom framework.
Imagine a pseudo function like this.
class Test
{
public function hi()
{
Event::add(__FUNCTION__ . 'is about to run.');
return "hi";
}
}
Imagine you need to do the same for some more functions. (Maybe you want to log which functions ran at the runtime and want to log them in a separate file.)
Instead of doing this and adding Events into functions manually, can we do something like this?
class Test
{
public function hi()
{
return "hi";
}
}
// events.php (It's a pseudo code so may not work.)
// Imagine extend's purpose is to inject codes into target function
Event::bind('on', $className, $methodName, function() use ($className, $methodName)
{
return $className->$methodName->extend('before', Event::add(__FUNCTION__ . 'is about to run.'));
});
The idea is to inject hi()
function which is inside Test class
and injecting whatever we pass in extend
function by outside. 'before'
means injection has to be at the first line of target function.
Finally, the events and event bindings are kept completely abstracted away from the functions. I want to be able to bind custom things without altering the functions.
I have a feeling that we can do this by hacking around with eval()
or by toying with call_user_func()
. I'm not sure, though. Using eval()
sounds pretty bad already.
My question is;
- Is it a possible thing to do with PHP?
- Does it has a name in OOP/OOP Principles so I can read further?
- Does it make any sense or is it a bad idea?
eval
. – Schreibercall_user_func
, though it may be awkward to configure. Note this 'decoration' style is used in many programming paradigms and frameworks - but you should be careful of performance concerns. Writing out to a file for every function call could kill any program you write. – Mudguard