Skip to content

Instantly share code, notes, and snippets.

@roquie
Last active March 22, 2016 07:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roquie/59db409851e882c23d4d to your computer and use it in GitHub Desktop.
Save roquie/59db409851e882c23d4d to your computer and use it in GitHub Desktop.
Laravel 5 Autoload Listeners from subscribe method.
<?php
/**
* Created by Roquie.
* E-mail: roquie0@gmail.com
* GitHub: Roquie
*/
namespace App\Traits;
use Illuminate\Contracts\Events\Dispatcher;
use ReflectionMethod;
trait AutoloadListeners
{
/**
* Register the listeners for the subscriber.
*
* @param Dispatcher $events
* @return array
*/
public function subscribe(Dispatcher $events)
{
$this->loadListeners($events);
}
/**
* @param Dispatcher $events
*/
protected function loadListeners(Dispatcher $events)
{
$reflect = new \ReflectionClass(static::class);
$listeners = array_filter($reflect->getMethods(ReflectionMethod::IS_PUBLIC), function($item) {
return substr($item->name, 0, 2) === 'on';
});
foreach ($listeners as $listener) {
$params = (new ReflectionMethod($this, $listener->name))->getParameters();
$events->listen(
array_map(function ($item) { return $item->getClass()->name; }, $params),
static::class . '@' . $listener->name
);
}
}
}
<?php
/**
* Created by Roquie.
* E-mail: roquie0@gmail.com
* GitHub: Roquie
*/
namespace App\Listeners;
use App\Events\RequestAccepted;
use App\Traits\AutoloadListeners;
use Illuminate\Log\Writer;
class LoggingSubscriber
{
use AutoloadListeners;
/**
* @var Writer
*/
private $log;
/**
* Create the event listener.
*
* @param Writer $log
*/
public function __construct(Writer $log)
{
$this->log = $log;
}
/**
* @param RequestAccepted $event
*/
public function onRequestAccepted(RequestAccepted $event)
{
$this->log->info(
'Description of Foo.',
get_object_vars($event)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment