对于需要降低模型间的耦合型,让关联记录的新增、其它服务的调用等拆分开,可以使用观察者模式
观察者模式实现了低耦合,非侵入式的通知与更新机制
Observer
在 AppServiceProvider
中添加观察者的绑定,例如员工与部门的管理,都易包括很多关联数据的变更:
public function boot ()
{
Staff::observe(StaffObserver::class);
Department::observe(DepartmentObserver::class);
//..
}
然后可以完善观察者的几个对应方法,例如请求钉钉、企业微信等第三方接口
public function created (Staff $staff)
{
//..
}
public function updated (Staff $staff)
{
//..
}
public function deleted (Staff $staff)
{
//..
}
Listener
而另一种解耦方式,是使用事件加监听者
在 EventServiceProvider
中配置事件与对应监听者的关联,以一个添加员工事件为例,添加时同时需要为公司的几个平台也增加账户:
protected $listen = [
\App\Events\Staff\StaffCreatedEvent::class => [
\App\Listeners\Staff\StaffCreated\CreateCrmStaff::class,
\App\Listeners\Staff\StaffCreated\CreateOaStaff::class,
\App\Listeners\Staff\StaffCreated\CreateBmsStaff::class,
],
]
在新增时添加一个 event()
方法来触发:
DB::transaction(function () use ($staff) {
$staffModel = Staff::findOrNew($staff['id']);
//...
$staffModel->save();
event(new StaffCreatedEvent($staffModel));
return $staffModel;
});
监听者的结构非常简单,主要完善好 handle()
方法
namespace App\Listeners\Staff\StaffCreated;
use App\Events\Staff\StaffCreatedEvent;
class CreateOaStaff
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct ()
{
//
}
/**
* Handle the event.
*
* @param StaffCreatedEvent $event
* @return void
*/
public function handle (StaffCreatedEvent $event)
{
//..
}
}