Skip to content

Commit 41acd56

Browse files
authored
Merge pull request #180 from Mahoke/feature/update-docs-listener-registration
Update docs about event listener registration
2 parents 89575c9 + 9b432a4 commit 41acd56

1 file changed

Lines changed: 8 additions & 40 deletions

File tree

docs/10-events-and-listeners.md

Lines changed: 8 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -152,55 +152,23 @@ function a_newly_created_posts_title_will_be_changed()
152152
}
153153
```
154154

155-
Now that we have a passing test for emitting the event, and we know that our listener shows the right behavior handling the event, let's couple the two together and create a custom Event Service Provider.
155+
Now that we have a passing test for emitting the event, and we know that our listener shows the right behavior handling the event, let's couple the two together and register our listener.
156156

157-
## Creating an Event Service Provider
157+
## Registering the Listener in the Service Provider
158158

159-
Like in Laravel, our package can have multiple service providers as long as we load them in our application service provider (in the next section).
159+
To let Laravel know which listeners should handle a certain event, we need to register the listener in the `boot()` method of your package's service provider:
160160

161-
First, create a new folder `Providers` in the `src/` directory. Add a file called `EventServiceProvider.php` and register our Event and Listener:
162-
163-
```php title="src/Providers/EventServiceProvider.php"
161+
```php title="BlogPackageServiceProvider.php"
164162
<?php
165-
166-
namespace JohnDoe\BlogPackage\Providers;
167-
168-
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
163+
use Illuminate\Support\Facades\Event;
169164
use JohnDoe\BlogPackage\Events\PostWasCreated;
170165
use JohnDoe\BlogPackage\Listeners\UpdatePostTitle;
171166

172-
class EventServiceProvider extends ServiceProvider
167+
public function boot()
173168
{
174-
protected $listen = [
175-
PostWasCreated::class => [
176-
UpdatePostTitle::class,
177-
]
178-
];
179-
180-
/**
181-
* Register any events for your application.
182-
*
183-
* @return void
184-
*/
185-
public function boot()
186-
{
187-
parent::boot();
188-
}
189-
}
190-
```
191-
192-
## Registering the Event Service Provider
193-
194-
In our main `BlogPackageServiceProvider` we need to register our Event Service Provider in the `register()` method, as follows (don't forget to import it):
195-
196-
```php title="BlogPackageServiceProvider.php"
197-
<?php
169+
// other things ...
198170

199-
use JohnDoe\BlogPackage\Providers\EventServiceProvider;
200-
201-
public function register()
202-
{
203-
$this->app->register(EventServiceProvider::class);
171+
Event::listen(PostWasCreated::class, UpdatePostTitle::class);
204172
}
205173
```
206174

0 commit comments

Comments
 (0)