You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/10-events-and-listeners.md
+8-40Lines changed: 8 additions & 40 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -152,55 +152,23 @@ function a_newly_created_posts_title_will_be_changed()
152
152
}
153
153
```
154
154
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.
156
156
157
-
## Creating an Event Service Provider
157
+
## Registering the Listener in the Service Provider
158
158
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:
160
160
161
-
First, create a new folder `Providers` in the `src/` directory. Add a file called `EventServiceProvider.php` and register our Event and Listener:
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
163
+
use Illuminate\Support\Facades\Event;
169
164
use JohnDoe\BlogPackage\Events\PostWasCreated;
170
165
use JohnDoe\BlogPackage\Listeners\UpdatePostTitle;
171
166
172
-
class EventServiceProvider extends ServiceProvider
167
+
public function boot()
173
168
{
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 ...
198
170
199
-
use JohnDoe\BlogPackage\Providers\EventServiceProvider;
0 commit comments