How to create a function that adds or calls an other function after an already called function. PHP -
im not sure name of this...i'd want make wordpress has. add_action
function calls function after function.
something this:
add_action('the_function()','the_function_to_add()');
alright, figured out how add function before one. possible add after one?
to add before : call_user_func('barber', func(), func2() );
adds func() , func2() before berber() function.
in wordpress add_action creates hook specific wordpress action. function called @ point action triggers itself.
this similar event dispatcher, add_action
acts dispatcher decouples code calling given function function itself. when event (the action) triggered, dispatcher can call registered functions.
as implementation, it's not found in php natively set of functions, created reasonably easily.
edit
here's 1 such implementation:
<?php class dispatcher { // event id callback functions array private $callbacks = array(); function subscribe($event_id, $callback) { if (!isset($this->callbacks[$event_id])) { $this->callbacks[$event_id] = array(); } $this->callbacks[$event_id][] = $callback; var_dump($this->callbacks); } function publish($event_id, $obj = null) { $callbacks = $this->callbacks[$event_id]; if ($callbacks) { foreach ($callbacks $callback) { call_user_func($callback, $obj); } } } } // object shared appropriate (hopefully can avoid global object!) $dispatcher = new dispatcher(); // code function receiver($obj) { echo "receiver got " . $obj; } $dispatcher->subscribe('test-event', 'receiver'); // somewhere else, possibly in else's code in different class $dispatcher->publish('test-event', 123); ?>
the output:
array(1) { ["test-event"]=> array(1) { [0]=> string(8) "receiver" } } receiver got 123
the first array understanding $callbacks
stores. whenever "test-event" event published, registered callback functions executed.
if wordpress, add_action
subscribe
in own code, , publish
do_action
called in wordpress' own code.
for simple example i've allowed arbitrary object passed during publish
.
finally, if you're working decent framework surely implemented somewhere in already, example shows how easy , useful can be.
Comments
Post a Comment