Laravel: Why Observers and Event Listeners are 'Risky'

preview_player
Показать описание
A little bit philosophical topic: when we're trying to offload some logic from the Controller to "somewhere", aren't we shooting ourselves in the foot, for the future?

- - - - -
Support the channel by checking out our products:
Рекомендации по теме
Комментарии
Автор

Just add an @see annotation in the controller class that points to the observer and you're done.

TavoNievesJ
Автор

I agree with that because the codes need to be transparent to the new developers, they might need to learn your code but if the code is hidden, there will be too many questions to ask. and thank you for enlightening us about the tips.

SinghatehAlagie
Автор

I agree with you. A lot of the "thin controller" strategies seem to be dogmatic rather than pragmatic. In the vast majority of cases I'd say a lot of design patterns are completely unnecessary *until* you actually need them - and the chances are you won't need them. My usual advice - especially to myself! - is to watch out for code duplication and once you've found something that repeats that's when you start a refactor and you see if there's a pattern that you *could* use or a feature of Laravel that might be appropriate.

martinh
Автор

If you only create a model inside a controller that could work. But if you might create a model in different places, you want the behaviour to be attached to the creating event, not the controller action.

mokhosh
Автор

Thanks for this nice video. I think the post-action (create, edit...) logic and maintainability are the end-goals here. I'm thinking:
- external service (Events & Listeners)
- database logic flow)

For
Just my opinion...

cliffordusidamen
Автор

Sometimes we need Observers and Events outside the controller! I think in this case the developpeur SHOULD add a comment mentioning what's happening under the hood

khafi
Автор

update for the issue at 2:50
This is now basicly 'fixed' with php attributes

just slap a on a model and it is easy to see that this model has a observer attached to it :)

only works in projects that support php 8 and use at least laravel 10.44 though

(in case anyone seeing this from now on)

JustPlayerDE
Автор

Love these types of videos! My vote for more philosophy!!! =)

fylzero
Автор

This is best Laravel channel! I just asked a senior dev yesterday why I would use Form Request Class when my controller was already so small. It seemed that it just made things harder to understand, especially for a newer coder. It seemed both ways had merit and uses.

randak
Автор

When ever I use Model Observers I leave a comment in the controller at the observer event location like


It keeps the controller clean and informs the developer about hidden code.

blank
Автор

I mostly build the Observer classes with "creating" and "created". In the observer class I then fire the events, such as sending a mail. I find that knowing that these methods are built into Laravel, you have a "one stop shop" to find an overview of what happens before and after. Always jumping to the events from the controller I find confusing. Thanks for the thought though!

konstruktion
Автор

Seems that a good use case for observers may be when the performed logic is not related to business rules. For example performing some task related to the application infrastructure.

BogosortLife
Автор

I noticed that many developers do not use functions like prepareForValidation and passedValidation in Request class. It is more comfortable to use strtolower there instead of manipulate data in event class

andreymikhalev
Автор

I agree. Although evens are more obvious than observers, sometimes it takes a while to track down the event listener.

alexrusin
Автор

I used to think this way — *Hehey! Let's confuse everyone (including me :P) about my code by abstracting all the logic behind modern features and design patterns. Then pretend to be a cool Laravel dev 😎*

But now, this video has entirely changed my mind and makes me remember *Terry Davis's* quote _" An idiot admires complexity while a genius admires simplicity"_ !

alnahian
Автор

I love laravel daily. Apart from Laracast this is my fav place to dig in Laravel stuffs. However, I would slightly disagree.

We can say there are two types of events. One is the defaults ones that Laravel models fires. i.e. Creating, Created, Saved, Deleted. For these we have Model Observers. There are many things that are more appropriate to be handled 'under the hood', for example assigning an uuid to $model->id whenever a model is 'creating'. A new developer doesn't always need to know about all the abstractions. Many of these abstractions are imposed not by laravel but your own architecture that you imposed on to of laravel.

However, you can create custom Events and observers for your own event like 'OrderShipped'. I agree, that these are not easy to track unless you have a good documentation on all the events you have fired and where they are listened.

Every advanced programming implementation has some sort of problem (or I would say trade off). I think the message from Mohd Said can get misinterpreted by the viewers. Yes - Event has problem, it is not visible. Laravel has problem because it slower than my one file PHP code and of course a new dev needs to spend hours learning it.

Events are core to modern day high transactional applications. And, any reason that sounds LIKE "New team members may not be familiar with %" is probably not always a very good justification.

However, what is said in this video is true. But a young lazy developer who want's to skip learning a few things, if he sees this video it gives him good motivation to skip the core concept of Event Driven designs.

RaihanSR
Автор

This time I have to disagree. If the only problem is the logic itself being "hidden" from yourself or your colaborators, then you just don't documented your code structure well. Observers are a very powerfull tool for centralizing Model layer logic outside of the Controller layer.

leonardoldr
Автор

Coming from a front-end developer's perspective where you have to use events and listeners because there is UI and asynchronous behavior involved, I started thinking that listeners were the right way also to code for a server-side application (Laravel specifically), which has no UI and is synchronous. But this clears it up for me why they aren't a good idea and really don't serve much purpose unless your application is meant to be extended. If you've written a CMS or some other application and want to expose the ability to hook into it, then listeners might be put to good use.

dans
Автор

My rule of thumb is that Observers are for enforcing invariants - something that should always be true about the model. For example, if any Post model MUST have a slug, or if the slug is changed there MUST be a Redirect record that ensures that old slug is 301-redirected to the new slug, I would put that login into an Observer. Keeping invariants true is crucial for production because it helps to avoid subtle bugs coming from inconsistent state that otherwise might accumulate with time. The benefit of Observer is that it runs always when an observed model is created/modified. Of course, with explicit calls inside a controller you see that some particular side effect takes place when creating a record. But that won't help you to remember that you have to call the same side effect when creating a model from inside a job or console.

I don't have a strong opinion about Events, but they feel like an antipattern for me inside synchronous code. On the one hand, it's perfectly okay to put sending email notification when a user is registered inside the controller. On the other, I don't think that really belongs to a controller. I think that controllers should be kept short, and if they need to do more that just a few method calls and passing data to a view, I would extract that logic into some separate service. There I wouldn't need events, because I could put any additional things I need to do into a separate method. Again, the rationale here is that I could invoke that logic from console, job, or inside a test as a whole, without risk to forget to send an email or fire an event.

pavelnosov
Автор

This is so true, one of my biggest gripes when I started working with Laravel. Observers and sometimes middleware can obfuscate system behaviours, which is a real pain to track down when you are not aware of them.

JoshuaHeagleDev