Skip to content

Instantly share code, notes, and snippets.

@ahsankhatri
Created August 1, 2016 07:34
Show Gist options
  • Save ahsankhatri/c1eaaf12182a33fe597b1be46e50f14a to your computer and use it in GitHub Desktop.
Save ahsankhatri/c1eaaf12182a33fe597b1be46e50f14a to your computer and use it in GitHub Desktop.
Simple and elegant way to attach hooks in your application
<?php
// Example 1:
Event::bind('blog.post.create', array(new BlogTriggers, 'onPostCreate'));
// Trigger for Example 1
Event::trigger('blog.post.create', [
'name' => 'My 123rd Post on Blog',
'id' => '123',
]);
class BlogTriggers {
public function onPostCreate($args=array()) {
echo "Post id <strong>{$args['id']}</strong> created with the title <strong>{$args['name']}</strong>";
// echo 'I am tiggered on Blog Post Created';
}
}
class Event
{
public static $events = array();
public static function trigger($event, $args = array())
{
if(isset(self::$events[$event]))
{
foreach(self::$events[$event] as $func)
{
call_user_func($func, $args);
}
}
}
public static function bind($event, $func)
{
self::$events[$event][] = $func;
}
}
// Source: http://stackoverflow.com/questions/4471183/php-event-listener-best-practice-implementation/9255855#9255855
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment