在开发中我们经常需要新增,修改、、、等模型操作 操作完成后需要触发个事件 以前一般的做法
<?php
//例子1
$row = User::InsertGetId(['name'=>''张三]);
if($row){
User::wehre('id',$row)->update([]);
return $this->json('操作成功');
}
---------------------------------------------------------
//例子2
class order{
public function addOrder(){
Log::update();
}
}
$order = new order();
$order->addOrder();
?>
以上两个例子是不是我们一般的做法 增加了操作上的复杂性 要去操作成功上述后进行下一步的操作
现在我们讲讲 观察者模式 设计原理
<?php
//被观察者接口
interface Observable{
function add(observe $observe);
function del(observe $observe);
function notify();
}
//订单被观察者
class order implements Observable{
private $instance=array();
function add(observe $observe)
{
// $this->instance[] = $observe; 将实例服务放进去容器里
$key = array_search($observe,$this->instance);
if($key === false){
$this->instance[] = $observe;
}
}
function del(observe $observe)
{
// $this->instance[] = $observe; 将实例服务放进去容器里
$key = array_search($observe,$this->instance);
if($key !== false){
unset($this->instance[$key]);
}
}
function notify()
{
// 通过循环调用对应的修改类
foreach($this->instance as $key=>$val){
$val->update();
}
}
}
interface observe{
function update();
}
class Email implements observe{
function update(){
echo '发送邮件';
}
}
class Message implements observe{
function update(){
echo '发送短信';
}
}
//客户端调用
$order = new order();
$order->add(new Email());//注入
$order->add(new Message());
$order->del(new Email());
$order->notify();//通知
?>
在laravel中我们可以使用 php artisan make:observer Artisan 命令可以快速建立新的观察者类:
laravel 在加载后通过 AppServiceProvider boot延迟注册 将 创建的观察者类注入