Laravel: Why Observers and Event Listeners are "Risky"

Поделиться
HTML-код
  • Опубликовано: 4 окт 2024
  • 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?
    Laravel Podcast episode "Queues, with Mohamed Said" www.laravelpod...
    - - - -
    Support the channel by checking out our products:
    Try our Laravel QuickAdminPanel: bit.ly/quickad...
    Enroll in my Laravel courses: laraveldaily.t...
    Purchase my Livewire Kit: livewirekit.com
    Subscribe to my weekly newsletter: bit.ly/laravel-...

Комментарии • 140

  • @TavoNievesJ
    @TavoNievesJ 3 года назад +32

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

  • @SinghatehAlagie
    @SinghatehAlagie 3 года назад +21

    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.

    • @ifeanyinnaemego
      @ifeanyinnaemego Год назад +1

      Bro howdy you have not uploaded the school management system in your channel

  • @fylzero
    @fylzero 3 года назад +30

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

  • @martinh4982
    @martinh4982 3 года назад +8

    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.

  • @khafi22
    @khafi22 3 года назад +7

    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

    • @Jurigag
      @Jurigag 3 года назад

      I don't think so. Main reason to use events and listener is to decouple logic. Many things can happen after saving user for example, you can have whatever listener you want, so i don't think comment is necessary - actually think of it as you developer in one team can produce async event - that user is saved, and other developer in other team could consume it and do something else, it would be stupid to comment that when saving there is something happening - this is pretty much coming back to coupling logic together, if you need such comment - then it's better just not to use event and put this code as some kind of service - which will be explicitly called there - of course it depends.
      This is why i don't like laravel events actually, we use symfony messenger which is much more flexible.

    • @Zach2825
      @Zach2825 3 года назад

      Took my words 😂

  • @cliffordusidamen6622
    @cliffordusidamen6622 3 года назад +6

    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 (Observers...transaction-based flow)
    For maintainability->Documentation.
    Just my opinion...

  • @blank001
    @blank001 3 года назад +15

    When ever I use Model Observers I leave a comment in the controller at the observer event location like
    // PostObserver@created is triggered to generate HashId
    It keeps the controller clean and informs the developer about hidden code.

    • @ritomukherjee8389
      @ritomukherjee8389 3 года назад +1

      Yes it's the best practice so far. I do the same. With this commenting paradigm been followed then only Observers, Events & Listeners are good and else who don't comment their code properly, it's always a pain for the next developer, even sometimes for themselves.

    • @GavinHewitt
      @GavinHewitt 3 года назад +1

      I do this too. Way too many times I couldn't figure out why stuff was happening, only to find out I've put functionality in an observer. At least with a mention of the observer in the controller I know where to look.

    • @ehsanbagherzadegantalkhoun1479
      @ehsanbagherzadegantalkhoun1479 3 года назад +1

      Yes exactly you can keep your code clear via simple comments.

    • @Jurigag
      @Jurigag 3 года назад

      I think this is a bad idea. You couple your code back by adding this comment, better to just explicitly move code from listener to some kind of service and just inject it in your controller and execute it there instead of adding comment.

    • @blank001
      @blank001 3 года назад

      @@Jurigag In this approach the code is not coupled by comments rather expresses the code behaviour and functionality (exactly what a comment should do), and basically at the end it is a function call so describing the functionality in comments is a basic and right way to do it. Your way of doing it is not wrong, just a little more lines of code for same functionality and better readablity for juniors in my perspective.
      In the end use whatever is easier and better understanding for you and your team.

  • @JustPlayerDE
    @JustPlayerDE 4 месяца назад +1

    update for the issue at 2:50
    This is now basicly 'fixed' with php attributes
    just slap a #[ObservedBy(MyObserver::class)] 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)

  • @mokhosh
    @mokhosh 3 года назад +13

    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.

    • @Shez-dc3fn
      @Shez-dc3fn 3 года назад +4

      then u would create a service class where u create the model and then call that class wherever..

  • @winter-survivor
    @winter-survivor 3 года назад +7

    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.

  • @alexrusin
    @alexrusin 3 года назад +5

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

  • @konstruktion
    @konstruktion 3 года назад +3

    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!

  • @RaihanSR
    @RaihanSR 3 года назад +7

    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.

    • @devsbuddy
      @devsbuddy 5 месяцев назад

      I agree with you. And i like the event driven application a lot as it makes operation of the application easy to manage and the fact that everyone talks about "A new developer won't know it" is kind of a bad thinking because as being an experienced developer you understand why events and other patterns are important and you can not skip these if a "new developer" don't know about it. We must encourage the new developer to learn new things.
      Also if you are getting a new developer for a project you will always do a KT (knowledge transfer) so he/she will have better knowledge about the project and while doing KT you will obviously tell him/her that we use this or that pattern so he/she will get it and know that this project will have some kind of pattern before working on the project and if they know about the pattern they will definitely find the place where the code is executed.

  • @randak37
    @randak37 3 года назад +2

    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.

  • @dans9456
    @dans9456 3 года назад +2

    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.

  • @andreymikhalev7464
    @andreymikhalev7464 3 года назад +1

    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

  • @pavelnosov6311
    @pavelnosov6311 3 года назад +2

    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.

  • @andywong2244
    @andywong2244 Год назад +1

    i love philosophical videos like this Povilas. makes me question and learn on how and when things (e.g. design patterns) should be used.

  • @JoshuaHeagleDev
    @JoshuaHeagleDev 3 года назад

    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.

  • @leonardoldr
    @leonardoldr 3 года назад +9

    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.

  • @JimOHalloran
    @JimOHalloran 3 года назад +2

    Coming from a Magento background where events and observers are an integral part of the system and in a lot of cases the bast way to extend or override parts of the system (in Magento 1 at least, Magento 2 added a lot), I'm happy that this patter is available in both forms in Laravel.
    I agree that what's observing an event or listening to a model event isn't alway clear. Trying to track down what's responsible for a certain thing happening isn't always easy with events and listeners. This can make it harder for a new developer on a given codebase to find their way around. But in some respects, this opacity is also somewhat of an advantage. Lets say you want to set a "created by" field on your model to the currently logged in user, and a developer not terribly familiar with the codebase is tasked with creating an additional form to create new instances of that model. With an observer aproach it's likely that no matter how the developer codes their corm controller the "created by" field gets set without them having to know that it exists and setting it themselves. It's a bit like Laravel's standard timestamp fields, it's great that they "just work" and we don't need to think about why they just work.

  • @alnahian2003
    @alnahian2003 Год назад +2

    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"_ !

  • @zHqqrdz
    @zHqqrdz 3 года назад +2

    I love to use Observers when I need to have a logging system, for example, a model that will have different states, and on every update of that model I want to add a record to a log table to persist each state. I would definitely hate to see an attribute being changed magically only when doing a creation or an update. Furthermore, I don't like events for that matter either as we want to do this in sync, and in my mind, the point of events is to delegate "optional" or "failable" logic, such as sending an email or starting a long job. We just dispatch an event, and then it lives on its own. It's not "required" to work, it's just better if it does. Instead, I would simply calculate/modify the attribute in either the controller if it's in one place only, or in a Service class otherwise.

  • @Sdirimohamedsalah
    @Sdirimohamedsalah 5 месяцев назад

    The observer it’s like a controller for event. I found this logic very useful

  • @AtomCoder
    @AtomCoder 2 года назад +1

    I agree. However, a simple descriptive comment explaining that the logic is handled via an observer or an event would direct the developer in the right direction.

  • @QaziHamayun
    @QaziHamayun 3 года назад +3

    Yes, Event->Listener is a problem especially while debugging (event/Listener). A year ago when I learned that how Laravel Event/Listener works, I used it in my code a various locations, but still it takes a hell of a time for debugging. while Laravel JOB is pretty straightforward. My opinion is, if you/anyone going to queue event->Listener then it would be better to use Laravel JOB

    • @Jurigag
      @Jurigag 3 года назад +1

      I disagree, you might want to decouple listener from queue event all together on some point - like move it to separate microservice, and then laravel job wouldn't make much sense there.

  • @pilotcoding7129
    @pilotcoding7129 2 года назад

    Perfect Video Have my Respect Sir, I've worked on Large scale applications which has to be this way for writing very transparent codes Just Like You & Muhammad Saeed Said.

  • @ianriizky
    @ianriizky 3 года назад +2

    What a very enlightening video I'm watching right now! Thank you for the inspiration 👍

  • @pritek90
    @pritek90 3 года назад +1

    Most examples on observers are just overengineering - manipulating on string making them slug, uppercase, lowercase etc. could be done directly in model on mutators, where IMO it would be "less hidden" then observer.

  • @JohnnyBigodes
    @JohnnyBigodes 3 года назад +2

    Really nice video... I love the queue system of laravel, but I am still a heavy user of observers and events. This is a team preference and when using these we use comments in the controller. I dont like the idea of using queues for everything that can be done in one or more events on the fly.

  • @austinakamelu6970
    @austinakamelu6970 Год назад

    Yea I agree, coming from a Nodejs and Rust background, I found that a lot of things in Laravel were not needed with time I saw the need for some but I feel like using an event to fire sending verification emails only to have a listener and all bound to it is much overhead, when I could just make a job and dispatch the job and then in its handle method do all I want to do

  • @Nodaschi
    @Nodaschi 3 года назад +1

    That is why I prefer to do small calculations on model (like vat calculation you mentioned) the old fashioned way via event registering in models boot method like in laravel 5.

  • @mohamednabih6036
    @mohamednabih6036 3 года назад

    I agree with you when modifying another programmer code. I spend a very long time understanding the problem, then a few minutes to solve it. It is possible to save all this time if the code is clear enough.

  • @charalamposkormenidis7178
    @charalamposkormenidis7178 3 года назад +1

    Very interesting video! So, my story on this one was back in laravel 5.6, where it was my first experience with the framework. I wanted to change the id of each model to uuid. Laravel's documentation recommended that you would write a function inside the model like self::creating and you would create the uuid inside there. But I forgot the uuid that I created in the controller before, so I would get different IDs before and after the creation. It took me an hour or so to find the problem, but I had pretty much the same experience. In this case, I just had a rule that the uuid creation would happen inside the self::creating function, so the end result was as expected.

  • @rudiwerner1930
    @rudiwerner1930 3 года назад

    Fully agree !!!!
    I've always had my doubts about the hype for slim controllers

  • @yamenashraf2495
    @yamenashraf2495 3 года назад

    You got a point, but can’t tell it’s risky, I find it very helpful and usable.

  • @Jurigag
    @Jurigag 3 года назад +1

    You should use event-listeners to decouple logic. For example if user is created - you want to send email, this can happen as well asynchronyously and your old code would still work.
    That's why writing some kind of comments that something happens after a save is a bad idea - because you couple them back by comment. Think about microservices - most of the time you need some way to communicate between them, and events are one of the way, you fire/dispatch an event on some queue system in one microservice - rabbitmq,sns,sqs,redis, and other service can use this event and do their logic, it would be weird if you go back to other microservice and write there a comment that other microservice uses this and do something with this.
    Also you should avoid cases where code executed in listener affects the synchronous code later or execution of this listener is even necessary. Perfectly you should be able to change transport of this event to asynchronous and your application should still work as it is.

  • @austinakamelu6970
    @austinakamelu6970 Год назад

    I’m a ‘don’t use it unless you really have to’ guy so in the case for Observers I didn’t use them until recently when I noticed I was caching posts and when someone muted a post it still got back the post, so I needed to observe the PostMute model and when it’s created I just refresh the cache

  • @bubunamawu
    @bubunamawu 3 года назад +1

    Hi love watching your videos. I agree with what you are saying but I think events have their place also. In particular to allow third parties to hook into code and execute custom logic. In the case of packages like the laravel framework events do just that.

  • @dclindner
    @dclindner 3 года назад +2

    You raise great points. The reason I might use an event is when it's important to create (maintain) a decoupling/separation between the source of the event and the listener. Perhaps they lie within different domains. The coupling between the event source and the listener functions can be entirely eliminated with events. I prefer jobs when the responsibility for the intended actions lies within the same domain. There is no reason to create separation in execution flow if, ultimately, the domain of responsibility remains the same, IMO. I wouldn't use events if the purpose is only to convert a synchronous operation to an asynchronous one--leave that to jobs. Using Observers, to me, is like trying to catch a falling knife. It's better to prevent the knife from falling in the first place than trying to catch it before it hits the ground. Sorry, too many words, I know. :-)

    • @Jurigag
      @Jurigag 3 года назад

      Exactly, the easiest way to think about event and listeners is this - they should be easly replaced by async event, and everything should work as it is. If those events and code executed in listeners affects synchronous code then you should rethink if using events is actually needed.
      Also events are really needed but when you have microservices architecture, then jobs aren't making a sense as other service can also listen to this event and do something totally else which your microservice doesn't have any knowledge about it. If you want to use a job, you pretty much coupling things back together. And there are cases where you specifcally want to decouple them.
      Laravel Jobs are telling you pretty much WHAT, like SendNotificationJob. And in perfect world you want to avoid what - just tell your system, potentially distribuited and with microservices, that user is created, and you don't care what happens later, or what other systems and microservices do with that message.

  • @baadrqaaba9529
    @baadrqaaba9529 3 года назад +1

    Love the approach, it make sense.

  • @parijke
    @parijke 3 года назад

    The "power" of events are that they allow for plugable behaviour. Great power comes with great responsability. It allows for altering processes without modifying existing code, which can be great.

  • @Lorado1991
    @Lorado1991 3 года назад

    Interesting idea and point of view, which makes sense. But still, there are definitely moments, where observers and listeners gives ability to achieve something with less effort. E.g. in our project we need to log any changes of particular models to the DB, so administrator (actually our chef) can comprehend made changes, as data may be changed by different users. We implemented it with Observers, written reusable code which works for each eloquent model, and it works like a breeze

  • @AliAwwad
    @AliAwwad Год назад

    I don't like having Observers as well, as when the application grows, you'll have some exceptions on Created or Updated that you dont want to run them in specific scenarios. Also this not only applies to new joiners to the project but also to myself when the project is few years old.

  • @Asiro-S
    @Asiro-S 3 года назад +1

    Actually, very interesting and lovely opinion, thank you for a video.

  • @ZainAli-uq3fj
    @ZainAli-uq3fj 2 года назад

    Maybe Taylor wrote email verification logic for new registered users as an event so that the same logic can be used in other parts of the application like when user updates his email in profile settings then `SendEmailVerificationNotification`.
    Writing logic for user email verification would not be ideal in UserObserver as you may not want to reuse that created() method on UserObserver when user updates his email.

  • @devendergupta_official
    @devendergupta_official 3 года назад +1

    Hmmm... I would say it's personal preference. Idk maybe I'm wrong, but I really don't mind keeping all the codes separate i.e using multiples listeners and jobs. Maybe in the controller function we can add comments to notify the developer that such design patterns are used for this function.

    • @rohannnsingh84
      @rohannnsingh84 3 года назад

      This works fine for small logics but when your logic or code become complex then it is a good practice to make different file or different function for better understanding that's why MVC came into existence ... IMO

  • @DanielŚmigiela
    @DanielŚmigiela 3 года назад

    i put into PHPDoc block info about using observer in method :)

  • @Atz22
    @Atz22 2 года назад +1

    I wish my controllers were this short 😂 often my controllers are quite long and I have thought of abstracting parts out but it's for this reason I don't as if I return to project to update or improve I don't want to spend ages just figuring out how the logic or code flows. It can mean a busy controller but it's a sacrifice I'm happy to make ...my 2c

  • @NoOorZ24
    @NoOorZ24 3 года назад

    I have had same philosophy ever since I started using Laravel and found out about event listeners and observers

  • @elandlord
    @elandlord 3 года назад +2

    I think observers are incredibly useful when it comes to repeating small parts of logic that should otherwise be individually defined elsewhere. Personally, the argument of “when a new (non-Laravel) developer is introduced to the project, they have no notion of what’s going on” is flawed, in the sense that this has to do more with the skill level of the developer. The same could be said about other design patterns (e.g. Repository, Strategy). A simple comment should suffice to inform future developers about the usage of the Observer pattern.
    Similarly, I guess using Events is a personal preference. Personally, I use Events and Listeners all the time. Especially when Events should trigger other Events. If a developer consistently uses Events in the application, the EventServiceProvider gives a great overview of the full capabilities of the application, since all logic is defined there. Events and Listeners should have descriptive names and have single responsibility. Yes, you have to manually check each file for the functionality. But defining individual Jobs loses the strength of triggering and chaining Events.
    Long story short: it’s a personal preference whether to use observers and events.

    • @LaravelDaily
      @LaravelDaily  3 года назад +1

      Yes, it is a personal preference. Or, getting back to the "new developer" idea, it's a TEAM preference. So in your case, do you work alone on your code, or with a team? In other words: are you alone in taking responsibility of all the decisions about design patterns you use? That question alone may affect a lot of decisions of how to structure the code, in my experience.

    • @elandlord
      @elandlord 3 года назад

      @@LaravelDaily Thanks for taking the time to respond. I agree with you! It's indeed a team preference, as long as everyone is informed, there is more than one correct solution. I personally work in a smaller team of full-stack developers, so these things can easily be discussed. For bigger teams this might be increasingly difficult.
      Additionally, the use case is important. Do you really need to use Events when you only have one listener? Very interesting topic to reflect on.
      Thanks for making these kind of videos, and have a nice day!

  • @Alex-nm9nr
    @Alex-nm9nr 3 года назад

    I agree, but still I love observers. And I prefer put a comment in controller like "//observer method fired"

  • @modestusmunh93
    @modestusmunh93 3 года назад

    I am not even junior developer, but I try to learn things like Observers, Events, etc. So I think new developers should know how to write (and read) existing code.

    • @modestusmunh93
      @modestusmunh93 3 года назад

      Or, according to your reasoning, you need to explain to beginners how to add 2 + 2.

  • @alicenNorwood
    @alicenNorwood 3 года назад

    Man of the year :)

  • @hnrc2
    @hnrc2 3 года назад +2

    I agree, but then, when is fine to use this features? Also, could you avoid "hide" information by using annotations/comments in the controller saying that an event/observer is executed after some action?

    • @FaizanAnwerAli
      @FaizanAnwerAli 3 года назад +1

      You don't use until you have no choice.
      Most often it happens when you're working on someone else code. And it's and it's has tons of code and it's currently live. And you can't alter the running functionality. That's where observer are helpful.
      For event, always emit event. So incase in emergency like the above case, you can listen event.

  • @awsometips1182
    @awsometips1182 3 года назад +1

    I guess the real problem here, is documenting our application. we need to document everything every time a feature is added because it's a must. for observers as with any design pattern, it comes to solve a problem if that problem doesn't actually exist we don't need to implement it.
    if our code didn't work as expected and we find it hard to find where the problem is, I think that we didn't do our unit test properly.
    what you think guys ?

  • @michalbabic8636
    @michalbabic8636 3 года назад

    I like observers and events. But observers are good only for simple logic like making slug. Nothing more. And annotation @see is necessary.
    Events are more difficult. I use events for everything, what can be queued, or which can follow up more actions, which unnecessarily enlarge the code. For example buy product -> send email, send rest api to 3rd party, make some changes to user preferencies, create some bonus points, etc.
    But things directly related to the purchase, such as deducting the discount I solve in the service layer.

  • @abelenocrodriguez
    @abelenocrodriguez 3 года назад +1

    Very good video, I hope you get better, I see that you are a little cold, greetings from Panama, I think the way you present is much more readable for a team, but that approach can be repeated if you use a service or an event, somehow you would still have to review the file, I think the use case should be when you exceed a certain amount of code in the controller to not reload the request to the server or third party services, there are many ways as I have been studying (events, services and jobs) encapsulate the code depends on the task you perform and the amount of code that involves (I use the translator, sorry for my grammar)

    • @LaravelDaily
      @LaravelDaily  3 года назад

      Thanks, yeah a bit cold, luckily not COVID :) But still able to shoot videos, so no big deal.

  • @xUnholyPrayerx
    @xUnholyPrayerx 3 года назад

    I remember multiple times debugging a project i inherited for this exactly was very hard to know which mutations are done when some of them are done in observers

  • @beanboi789
    @beanboi789 3 года назад +3

    Events aren't there to turn 10 line controller methods into 2 lines. They are there to turn 50 line methods into 20 line methods.
    I honestly don't understand the hate for events. If you just use an event class you can search for it by name. It's the same amount of effort as looking up a service class or anything else.

  • @dbelyaev
    @dbelyaev 3 года назад +2

    Povilas, please, migrate to fanless M1 Mac. From 1:26 huge fan blowing noise has blown out ears through the headphones 🤨

    • @dbelyaev
      @dbelyaev 3 года назад +2

      Ok. Got notification at 3:38.

  • @mfonabasiudobiambrain7134
    @mfonabasiudobiambrain7134 2 года назад

    A comment can be added pointing to the listeners. Have we forgotten about writing comments in our application

  • @FarshidCichi
    @FarshidCichi 3 года назад

    very nice, thank U man :)

  • @Stoney_Eagle
    @Stoney_Eagle 3 года назад

    The only 2 "hidden" events are inside the models on create and on delete, when a user is created I create a UID for the ID field and on delete I delete all relations and pivots.
    I don't like code that I can forget myself because I don't see it and then fight something I've created myself later, so I do prefer to call functions myself.
    If the code doesn't explain itself, it can't hurt to add a one liner that starts with // 🤣😉

  • @shubhamsahuSD
    @shubhamsahuSD 10 месяцев назад

    On the created method isDirty will work or not ?
    Or will it work only with creating.

  • @saidbenhmed7884
    @saidbenhmed7884 2 года назад

    I agree but we still need to use Events and listenners , there is a need for them and sometime thy're the best way to do some stuff . it depends on the application that you're trying to build and you own logic . thanks laravel daily you're the best .ps

  • @pollafattah7062
    @pollafattah7062 2 года назад

    I am using Traits to create functions for that matter

  • @عثمانالصيغ
    @عثمانالصيغ 3 года назад

    yes i agreed with you. i was partisibating in a ongoing porject and when i creat company i saw it in DB creating twise. so i relised that somthing happen in other erea so i foung another creating happens in observer

  • @SGDominicana
    @SGDominicana 3 года назад

    I can see the benefit of dispatching a job for performance, but I cant see much benefit in firing an event in the code (declaratively) over just calling some service.

  • @shaikhfoysal4426
    @shaikhfoysal4426 3 года назад

    Love this Thank you

  • @thisisthelogic
    @thisisthelogic 3 года назад

    The best channel!

  • @salvatoremilitello7356
    @salvatoremilitello7356 3 года назад +3

    Who don t simply use a Line of comment on top of method to info other developers that an observer is used for the model? Sometime comments are useful.

    • @enigmatics-lives
      @enigmatics-lives 3 года назад +2

      It may be important entity, that in use everywhere in project. Then you’ll have to put such comments everywhere

    • @marcusgaius
      @marcusgaius 3 года назад

      @@enigmatics-lives Isn't that better than making the code too verbose?

    • @Jurigag
      @Jurigag 3 года назад

      But main reason to use events - listeners is to decouple logic, this way you couple it back but with comment - easier to just put this code from listener to be after the code executed which fires the event.

    • @marcusgaius
      @marcusgaius 3 года назад

      @@Jurigag It is decoupled. You could just as well document it outside of the code.

    • @Jurigag
      @Jurigag 3 года назад

      @@marcusgaius what you mean outside of code? Like in some graph to mark the relations of events and listeners? Yea that makes sense and about this i agree.

  • @leonvanrijswijk8409
    @leonvanrijswijk8409 3 года назад +1

    I agree keeping the code in the controller. Maybe an event if the same action (for example registering a user) is performed on various places in the application.

  • @codelaravel
    @codelaravel 3 года назад

    Can we use paginate function by using repositories ?

  • @jasonmason3488
    @jasonmason3488 2 года назад

    I use Observers only to clear model cache after CRUD

  • @otsi9952
    @otsi9952 3 года назад +1

    How could someone consider example being good where price comes from the request (User Input). Do not do that !

  • @hatsikmaroukian4111
    @hatsikmaroukian4111 3 года назад

    Hey povilas, where can I learn more for various design patterns and various methodology on how to set/design laravel applications

    • @LaravelDaily
      @LaravelDaily  3 года назад

      laraveldaily.teachable.com/p/how-to-structure-laravel-project - I guess my course could help

  • @AsifBabaev
    @AsifBabaev 3 года назад

    pls add links to video that you mention on this

  • @m.Baobaid
    @m.Baobaid 3 года назад

    Hi there,
    I do have a suggestion about your next video, which is how to translate carbon date, time etc....
    for example using {{ date('M d, Y',strtotime($something->created at)) }}
    then it will be displayed as -> Apr 03, 2021
    my question how can we translate "Apr" to other languages, i have spent more than 3 days on this case searching for a possible way in the last 3 days, but there was no luck :(, if you could help me and the other who need this solution

    • @LaravelDaily
      @LaravelDaily  3 года назад

      I think you should read this: carbon.nesbot.com/docs/#api-localization

  • @borissman
    @borissman 3 года назад +3

    And, btw, i dont think its "philosophical". Its practical if anything

  • @DRMOHAMEDKHDR
    @DRMOHAMEDKHDR 3 года назад

    Repected view, thanks

  • @IlPandax
    @IlPandax 3 года назад

    Even if I use Laravel since 5.2, I've never used queue. May I ask you for a video about it? Thanks!

    • @LaravelDaily
      @LaravelDaily  3 года назад +3

      Maybe you never *needed* to use queues, and that's ok. Yes I'm planning to shoot video(s) about it, a bit later in 2021.

    • @IlPandax
      @IlPandax 3 года назад

      @@LaravelDaily I'm looking forward to it! :D

  • @L-A-O-S
    @L-A-O-S 3 года назад +1

    How to parse million lines from the file using job? It must be recursive?

    • @L-A-O-S
      @L-A-O-S 3 года назад

      How to exchange data between few jobs? Using cache?

    • @brianngetich007
      @brianngetich007 3 года назад

      I'd honestly recommend you read Laravel queues in action - Mohammed Said. It has a lot of insight regarding queues. For the synchronization things what exactly are you trying to achieve?

    • @L-A-O-S
      @L-A-O-S 3 года назад

      @@brianngetich007 I need to parse products from file, where each product starts from new line.

    • @brianngetich007
      @brianngetich007 3 года назад

      Do we have like if one fails, everything else fails? Or is every line independent?

    • @brianngetich007
      @brianngetich007 3 года назад

      For the first case using job batching would be a good idea since you can trace if a job failed or not. For the second one, you use a single job to dispatch every single line read to a simpler job such that even if one jib fails the rest will continue. You can then record the jobs that failed and later troubleshoot

  • @rosselliot8971
    @rosselliot8971 3 года назад

    Observers definitely are hidden code--magic code--and that kind of thing makes me uneasy.
    I'm not quite sure why Said was more in favor of jobs than events. Both are clearly obvious in the controller and both require a lookup to see what the listener or job handler is doing, so I see no difference there.

    • @LaravelDaily
      @LaravelDaily  3 года назад

      I fully understand him. If you see a Job in IDE, you can click there and land exactly on what it does.
      If you see an event, you need to manually search for all the listeners to find out what would happen after that event.

    • @rosselliot8971
      @rosselliot8971 3 года назад

      @@LaravelDaily No, I mean that with an observer it is totally hidden. An event/job is shown in the controller so you have a reason to look further.

  • @bashardlaleh2110
    @bashardlaleh2110 3 года назад

    Didn't really need a video for this, could've done it in a post

    • @LaravelDaily
      @LaravelDaily  3 года назад

      Sorry.

    • @bashardlaleh2110
      @bashardlaleh2110 3 года назад +1

      @@LaravelDaily don't be please, i was just giving positive criticism i appreciate what you do 🏵

  • @LaimonasNarbutas
    @LaimonasNarbutas 3 года назад +1

    KISS ;)

  • @javedkarim
    @javedkarim 2 года назад

    Good philosophical points however it's a learning curve problem for a developer, not a pattern problem. Furthermore, please don't cherry-pick what needs to be in the Controller and what's not. This Is very confusing for the developers.

  • @excodex8265
    @excodex8265 3 года назад

    I would not hate this pattern only coz it hides the process and is not synchronous.

  • @jobsphil9553
    @jobsphil9553 3 года назад

    Well. I don't agree with this point. Every developer including new fresh guy must understand the whole system. And it should be guided by senior developer.

  • @subadrunvlr
    @subadrunvlr 3 года назад

    please zoom your screen sir

  • @borissman
    @borissman 3 года назад

    YES! i agree!

  • @yummyanchor
    @yummyanchor 3 года назад

    the observeer is too convenient to deny it

  • @midnightlead
    @midnightlead 3 года назад

    Learn react philosophy and enjoy the power of functional programming. Be smart and let the force be with you