Last active
March 22, 2016 07:41
-
-
Save roquie/59db409851e882c23d4d to your computer and use it in GitHub Desktop.
Laravel 5 Autoload Listeners from subscribe method.
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 | |
/** | |
* Created by Roquie. | |
* E-mail: [email protected] | |
* 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 | |
); | |
} | |
} | |
} |
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 | |
/** | |
* Created by Roquie. | |
* E-mail: [email protected] | |
* 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