Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * This class porpose is to execute a code once on the next request using the session as a place to register
- * an instance of the class and execute the code when the object is being unserialized
- *
- * Created by: Amit Dar
- * Website: http://www.i-Dev.co.il
- */
- class NextRequestScheduler implements Serializable
- {
- private $executable_function = null;
- private static $session_var_name = 'next_request_scheduler';
- public function __construct($function_name)
- {
- if(!function_exists($function_name))
- {
- throw new BadFunctionCallException("Passed argument is not a valid function name");
- }
- $this->executable_function = $function_name;
- $_SESSION[self::$session_var_name][] = $this;
- }
- /*@see Serializable::serialize() */
- public function serialize()
- {
- return $this->executable_function;
- }
- /* @see Serializable::unserialize()*/
- public function unserialize($serialized)
- {
- call_user_func($serialized);
- $this->executable_function = null;
- /* unfortunatelly it's impossible to clean up the $_SESSION variable
- * from used instances, since $_SESSION array is not yet populated
- * at the moment of the unserialize function's call.
- *
- * Either you clean it up in a later stage or never clean it up.
- * Possibly, clean old instances out when constructing new instances
- */
- }
- }
- /******************* USAGE ***********************/
- $closures_dont_work = function() { echo 'hola from closure'; };
- function say_hi() { echo 'hi'; }
- function say_hello() { echo 'hello'; }
- session_start();
- new NextRequestScheduler('say_hello');
- new NextRequestScheduler('say_hi');
- //new NextRequestScheduler($closures_dont_work);
- /* The only way to use closures here is to fetch their source code
- * store it in the session and execute it on the next request.
- * Fetching closures source code is possible reading the file having the declaration
- *
- * A better way would be to invoke a member of a class (say user->get_new_forum_posts)
- * and that would require reimplementing the "unserialize" function to use call_user_method
- * rather then call_user_func.
- *
- * Adopt it carefully
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement