Currently, we have to register manually each observers of each models in the EventServiceProvider like that :
Model::observe(ModelObserver::class)
In big projects, we have to write so much lines (1 by model) that could be avoided with some conventions.
The idea is to automatically register models observers if they share the same path in their own namespaces.
In all my projects, i add this function in EventServiceProvider and change the namespaces to fit with the project namespaces.
public function bootObservers()
{
$files = Finder::create()->files()->in(app_path() . '/Api/Core/Models');
foreach ($files as $file) {
$className = str_replace('/', '\\', str_replace('.php', '', $file->getRelativepathname()));
$observerClassName = "App\\Api\\Core\\Observers\\".$className.'Observer';
if (class_exists($observerClassName)) {
$class = "App\\Api\\Core\\Models\\".$className;
$class::observe($observerClassName);
}
}
}
The other solution is to automatically add Model::observe(ModelObserver::class) in EventServiceProvider when php artisan make:observer command is called, but i personnaly don't like this method.
I'm aware that this only provide comfort and it's not essential, this is why i plan to build an external package for that.
But before, i would like to be sure that this couldn't be usefull in the Laravel core codebase.
If so, i'll write a draft pr. If not i'll build a package.
"Convention over configuration"
Currently, we have to register manually each observers of each models in the
EventServiceProvider
like that :In big projects, we have to write so much lines (1 by model) that could be avoided with some conventions.
The idea is to automatically register models observers if they share the same path in their own namespaces. In all my projects, i add this function in
EventServiceProvider
and change the namespaces to fit with the project namespaces.The other solution is to automatically add
Model::observe(ModelObserver::class)
inEventServiceProvider
whenphp artisan make:observer
command is called, but i personnaly don't like this method.I'm aware that this only provide comfort and it's not essential, this is why i plan to build an external package for that. But before, i would like to be sure that this couldn't be usefull in the Laravel core codebase. If so, i'll write a draft pr. If not i'll build a package.
Good day to all of you.