Enqueue a function (like wordpress add_action)

≡放荡痞女 提交于 2019-12-06 09:41:45

问题


How do I queue functions in PHP? I need something that works just like Wordpress's add_action system. I want enqueue function which then runs when the time is right.

Edit

This seems to work perfectly. Anyone got any tips to improve my code?

 $enqueued_actions = array();

 /**
  * Enqueue an action to run at a later time.
  * @param string  $hook The hook name.
  * @param obj  $func The function object.
  * @param integer $imp  The level of importance from 0-9
  */
 function add_action($hook, $func, $imp = 0) {

     global $enqueued_actions;

     $enqueued_actions[$hook][] = array('func' => $func, 'imp' => $imp);
 }

 /**
  * Run the enqueued actions with the correct hook.
  * @param  string $hook Hook name.
  */
 function run_action($hook) {

     global $enqueued_actions;

     $actions = $enqueued_actions[$hook];

     for($i = 0; $i < 9; $i++) {
         foreach($enqueued_actions[$hook] as $action) {
             if($action['imp'] == $i) {
                call_user_func($action['func']);
            }
         }     
     }

 }

回答1:


You are on the right track here. You might want to make the hooks persistent, though, i.e. saving the hooks into a database, a CSV file, an XML object model, etc.

Also, you might want to introduce a function for the sake of calling all the actions that have been latched to a certain hook, something like call_actions($hook);



来源:https://stackoverflow.com/questions/8870387/enqueue-a-function-like-wordpress-add-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!