## 观察者
路径:app/Observers
示例:
**定义观察者**
app/Observers/BlockObserver.php
```php
namespace App\Observers;
use App\Models\Block;
use Illuminate\Support\Facades\Auth;
// creating, created, updating, updated, saving,
// saved, deleting, deleted, restoring, restored
/**
* 区块观察者
*
* Class BlockObserver
* @package Wanglelecc\Laracms\Observers
*/
class BlockObserver
{
public function creating(Block $block)
{
$block->object_id || $block->object_id = create_object_id();
$block->created_op || $block->created_op = Auth::id();
$block->updated_op || $block->updated_op = Auth::id();
}
public function updating(Block $block)
{
$block->updated_op = Auth::id();
}
public function updated(Block $block){
Block::clearCache($block->object_id);
}
public function saving(Block $block){
if(is_array($block->content) || is_object($block->content)){
$block->content = json_encode($block->content, JSON_UNESCAPED_UNICODE);
}
}
}
```
> 可通过 Laravel 提供的 `php artisan make:observer` 自动生成
**注册观察者**
在 `AppServiceProvider` 服务提供者的 boot 方法中:
```php
.
.
.
public function boot(){
\App\Models\Block::observe(\App\Observers\BlockObserver::class);
}
.
.
.
```