问题
So I am learning about design patterns and I am currently studying the Observer pattern.
To implement it on a raw basis, I did something like this:
<?php
class Subject
{
private $foo;
private $bar;
private $observers = [];
public function addObserver(Observer $o)
{
$this->observers[] = $o;
}
public function removeObserver(Observer $o)
{
if(($key = array_search($o, $this->observers, $TRUE)) !== FALSE) {
unset($this->observers[$key]);
}
}
public function notify()
{
foreach ($this->observers as $observer) {
$observer->update($this->foo, $this->bar);
}
}
public function setFoo($foo)
{
$this->foo = $foo;
}
public function setBar($bar)
{
$this->bar = $bar;
}
}
interface Observer{
function update($foo, $bar);
}
class Observer1 implements Observer
{
private $foo;
private $bar;
public function update($foo, $bar){
$this->foo = $foo;
$this->bar = $bar;
}
public function display()
{
echo "Observer1 : Foo -> " . $this->foo . " Bar -> " . $this->bar . "\n";
}
}
class Observer2 implements Observer
{
private $foo;
private $bar;
public function update($foo, $bar){
$this->foo = $foo;
$this->bar = $bar;
}
public function display()
{
echo "Observer2 : Foo -> " . $this->foo . " Bar -> " . $this->bar . "\n";
}
}
$subject = new Subject;
$observer1 = new Observer1;
$observer2 = new Observer2;
$subject->addObserver($observer1);
$subject->addObserver($observer2);
$subject->setFoo(5);
$subject->setBar(10);
$subject->notify();
$observer1->display();
$observer2->display();
$subject->setFoo(20);
$subject->setBar(40);
$subject->notify();
$observer1->display();
$observer2->display();
So I see that the observers are getting updated. Is this the correct way to implement the observer pattern? I guess I could abstract the functionality in the Subject to add, remove and notify into its own abstract class. I could also user the SplSubject
and SplObserver
that PHP provides. What else can be done here to make this code better?
But what I really want to know is where is the Observer pattern used in Laravel. It must be in use somewhere in the framework and I can learn from it. Secondly, what are the practical applications for this? One of the things that I could think of is when I am doing caching in laravel and a model gets updated, it might need to notify the cache objects to change. Is this a good practical application of the pattern? What others are there?
回答1:
In my project I used Observers to check if A model has changed and throw event if changes have been made.
Let say I have Observer for my User Model hence UserObserver. What the observer does is it checks for changes in my user. And if there is changes.
I have a event handler to save transactions.
E.g "John Doe has updated his first name from Mike to John"
Where first name is a field in my User Model named first_name; There is more to observers and one is my application.
来源:https://stackoverflow.com/questions/39267139/how-to-practically-use-the-observer-pattern-in-laravel