DEV Community

marius-ciclistu
marius-ciclistu

Posted on • Originally published at marius-ciclistu.Medium on

Maravel-Framework 10.56.0 Improves Boot Time For Events and Observers


Maravel-Framework

Inspired by this discussion, I noticed that the developer convenience was slowing down the execution for registering events (cached or not) and observers.

To fix it, I added to event:cache command also the observers in this PR .

php artisan event:cache
Enter fullscreen mode Exit fullscreen mode

Also I improved how the cached events and observers are registered to cut some execution steps and improve the boot time for applications listening to multiple evens via event listeners or observers.

In Maravelith, if you put in the EventServiceProvider.php:

    /**
     * @inheritdoc
     */
    public function shouldDiscoverEventsAsObservers(): bool
    {
        return true; // do not set this to true if you don't cache the events because it involves reflection.
    }
Enter fullscreen mode Exit fullscreen mode

the observe() model method should not be called anymore but the observers public method names must have as typed param the Model that needs to be observed. Also the observers must be placed in Observers folder, analog with Listeners.

Bonus:

Maravel can benefit from these changes and use Observers like this:

<?php

namespace App\Observers;

class ExampleModelObserver
{
    public function updated(\App\Models\ExampleModel $setup): void
    {
        //
    }
}
Enter fullscreen mode Exit fullscreen mode

And now you can register this observer as Listener in EventServiceProvider.php (the observe() call should not be done!):

<?php

namespace App\Providers;

use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
// \App\Events\ExampleEvent::class => [
// \App\Listeners\ExampleListener::class,
// ],
        'eloquent.updated: ' . \App\Models\ExampleModel::class => [
            \App\Observers\ExampleModelObserver::class . '@updated',
        ],
    ];
}
Enter fullscreen mode Exit fullscreen mode

For these to work Maravel also needs:

$app->withEloquent();
$app->register(App\Providers\EventServiceProvider::class);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)