logo
podcast Podcast
get help Get Unstuck

Additional thoughts about the `observedBy` attribute

Another reason you might choose to use it

Joel Clermont
Joel Clermont
2024-10-08

Last week, I shared a small gotcha I ran into with the observedBy attribute.

That tip prompted some excellent reader feedback, which I think adds to the discussion, so I wanted to share it with you today.

Alex Bouma brought up the subject of performance. The older style of registering observers in a service provider means that all the wiring was done for every observer on every single boot of the app.

With the observedBy attribute, the wiring is only done for a model when it's actually used. This might not matter in most applications, but if you had many observers, this could be a useful performance improvement.

In fact, before this new attribute was introduced, Alex even wrote a package to offer an alternate model-specific approach.

And in case you're wondering, Laravel is smart about booting the model, so if you create 100 instances of a model, that wiring only needs to be done once per model, not once per instance.

In general, I like standardizing on newer syntax as Laravel introduces it, but this is one additional reason to consider using the new observedBy attribute, especially if you have a lot of observers wired up.

Here to help,

Joel

P.S. Don't be shy, feel free to reply if you ever have something to share. Or join the Mastering Laravel community and get a discussion going there.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.