Last active
December 10, 2019 00:24
-
-
Save ryantbrown/726b7ea4b82c3c0a22a0 to your computer and use it in GitHub Desktop.
Laravel 5: Dynamic Events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// creating new event handlers by extending Handler and | |
// store them in a "Handlers" directory to be read by | |
// the service provider, which will loop through the | |
// directory and Event::subscribe to each one. | |
// Make sure you prefix each handler method with | |
// "on" (ex: onUserRegister) as only these methods | |
// will be listened for. | |
// base event handler | |
abstract class Handler { | |
public function subscribe($events) | |
{ | |
// get name of instantiated concrete class | |
$class = get_called_class(); | |
// loop through each method of the class | |
foreach(get_class_methods($class) as $method) { | |
// if the method name starts with 'on' | |
if(preg_match('/^on/', $method)) { | |
// attach the event listener | |
$events->listen($this->key($method), $class.'@'.$method); | |
} | |
} | |
} | |
protected function key($name) | |
{ | |
// remove on from beginning | |
$name = ltrim($name, 'on'); | |
// prepend uppercase letters with . | |
$name = preg_replace_callback('/[A-Z]/', function($m) { return ".{$m[0]}" }, $name)); | |
// remove trailing . | |
$name = ltrim($name, '.'); | |
// now that we have the dots we can lowercase the name | |
$name = strtolower($name); | |
} | |
} | |
// service provider | |
use Illuminate\Support\ServiceProvider; | |
use ReflectionClass; | |
class EventServiceProvider extends ServiceProvider { | |
private function fullyQualifiedClassName($file) | |
{ | |
return 'Your\Namespace\\'.str_replace('.php', '', basename($file)); | |
} | |
public function register() | |
{ | |
foreach($this->app['files']->files(__DIR__.'/Handlers') as $listener) { | |
$class = $this->fullyQualifiedClassName($listener); | |
if(ReflectionClass::isInstantiable($class)) { | |
$this->app['events']->subscribe($class); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment