Have you ever heard anything about the single responsibility principle? I hope so. It is one of the SOLID principles in programming, and it basically says that a class has one and only one responsibility. In other words, every class has to do one single thing and not anything else.
Usually, when you build the first version of software, everything goes fine. Then, it happens. Your boss calls: time to introduce a new feature, developer! Especially if update means insert this little extra behavior here, your code base easily becomes heavy and sloppy.
Terribly sloppy! Then, you fight against deadlines, tests, Q&A, and so on, literally an odyssey. Not a very good practice, right?
Now, in the software development world, you can find many techniques and methods to add new features to your software in an elegant way. You have probably heard about events in programming.
In a few words, let’s say it consists of logic such as this: when X does this, then Y must do that.
Imagine a similar situation in your application: you just finished your application and then you say, “Oh, I just forgot to send an e-mail to the newbie user!”
With Eloquent, you can handle this situation in two ways. The first way is using the very interesting concept of model events. The second way is based on a more advanced concept: model observers.
In this chapter, in the first place, you will learn everything about events in the context of Eloquent models. Then, I will cover model events: what they are and when you would use them.
Then, I will do the same for model observers. You will learn all the differences, and the pros and cons. Obviously, for both of the concepts, I will use a practical example to show how to use them in a real-world situation.
Are you ready, hero?
- When should I use events in my models?
- Model events
- An example of model events
- Model observers
- An example of model observers