- Published on
How Laravel Simplifies Observers
- Authors
- Name
- Karani John
- @MKarani_
Sometimes, you may need to trigger some events in your code and maybe you don't want to do it in the controller or another place where the code would be messy. Observers are handy with such problems and will help you maintain a clean codebase. We will look at the observer pattern and how laravel simplifies this process.
its Friday, its blog day.
Today we will be talking about eloquent observers. Recently, I was building a forum and one of the neat ways to enable notifications is to use observers. If you are into design patterns, you have probably come across observer pattern.
The observer pattern is where an object(subject) will maintain a list of dependencies(observers) and notifies them of any state change. If you are writing raw php, then this would come in handy so much in your application.
Let's do a simple example where we need to notify a user that they have received a reply of their latest blog for example
interface Subject {
public function attach(Observer $observer);
public function notify($reply);
}Here we define the function which the subject(BlogPost) will implement. The attach will take an observer and add it to the array of observers. The notify function will take the reply and "broadcast" it to the observing objects in the array.
class BlogPost implements Subject {
// some other func
public function attach(Observer $observer) {
$this->observers[] = $observer;
}
public function notify($reply) {
foreach ($this->observers as $observer) {
$observer->update($this, $reply);
}
}
public function addReply($reply) {
// Save the reply to the database
// Assuming some database logic here
// Notify observers
$this->notify($reply);
}
}As you can see, our observer class must have an update function which must be invoked. So we will define an interface and a our observer class
interface Observer {
public function update(Subject $subject, $reply);
}class EmailNotification implements Observer {
// some other logic
public function update(Subject $subject, $reply) {
// Simulate sending email notification
echo "You have received a reply to the blog post.\n";
}
}We can register our observer(which does email notification) by attaching to the subject, simply:
$blogPost = new BlogPost();
// Attach email notification observer
$emailNotification = new EmailNotification();
$blogPost->attach($emailNotification);
// Simulate adding a reply
$reply = "Great explanation! Thanks for sharing.";
$blogPost->addReply($reply);And we can now notify the user when they received a reply through email. As you can see, we can add more observers depending on what we need to do with the reply. Send in app notifications, broadcast an event, send an invoice etc and maintain a quality codebase.
but laravel, โ
Laravel has these observers inbuilt in their eloquent models. The observers will watch for any changes in the model. If you want to set up an observer in your model when say a post is created, maybe you want to log that to an external logger for example. We simply:
php artisan make:observer PostObserver --model=PostThis will create a PostObserver that will watch for the following events:
<?php
namespace App\Observers;
use App\Models\Post;
class PostObserver
{
public function created(Post $post): void{}
public function updated(Post $post): void{}
public function deleted(Post $post): void{}
public function restored(Post $post): void{}
public function forceDeleted(Post $post): void{}
}As you may notice, we are given the collection of the model created and we can add our logic inside these functions depending on events. This makes it easy to develop applications faster. In our Post model, we can go ahead and add the attribute #[ObservedBy([UserObserver::class])]
use App\Observers\PostObserver;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
#[ObservedBy([PostObserver::class])]
class Post {}And that's about it. Our observers will be attached and when a post is created your logic in the create function will be invoked. This is usually used with notify but there are other ways you can get creative. The amount of code we would need to write if writing a custom observer would be alot but now we get a clean codebase and maintainable code.
If you are dealing with database transactions, you can go over the docs on that part Here
Otherwise, hope you learnt about the observer pattern and how laravel makes it easy for you to do it with less code. I love laravel and so should you lol
Be happy!!๐