正如一些 cmets 所指出的,您可以为此编写自定义 Artisan 命令。运行命令开始“侦听”触发事件。
在 PostgreSQL 中,您可以创建一个触发器,其作用类似于 Laravel 中的订阅者——观察表的变化,它收集表名和操作等数据,如果 Laravel 定义了连接,则通过pg_notify 将其传递给 Laravel到这个数据库。您可以使用 JSON 处理对数据进行编码以传递给 Laravel,然后将其解析为 JSON 编码为字符串。
这是一个简单的示例,用于查看 Orders 或 Users 表的 UPDATE、INSERT 或 DELETE。
触发器
create function notify_event() returns trigger
language plpgsql
as
$$
DECLARE
notification json;
BEGIN
-- PostgreSQL auto-defined variables:
-- TG_OP ~ action such as INSERT, DELETE, UPDATE
-- TG_TABLE_NAME
-- Contruct the notification as a JSON string.
notification = json_build_object(
'table',TG_TABLE_NAME,
'action', TG_OP);
-- Execute pg_notify(channel, notification)
PERFORM pg_notify('events', notification::text);
-- Result is ignored since this is an AFTER trigger
RETURN NULL;
END;
$$;
alter function notify_event() owner to YOUR_DATABASE_NAME_HERE;
工匠指挥部
<?php
namespace App\Console\Commands;
use App\Events\OrderCreated;
use App\Events\OrderDeleted;
use App\Events\OrderUpdated;
use App\Events\UserCreated;
use App\Events\UserDeleted;
use App\Events\UserUpdated;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* Class SubscribeToTriggers
*
* @package App\Console\Commands
*/
class SubscribeToTriggers extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'psql:subscribe-to-triggers {--t|table=* : Tables to synchronize.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Listen for changes on database and update the platform accordingly';
/**
* Tables to synchronize.
*
* @var array
*/
protected $tables;
/**
* @var
*/
private $subscribers;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->tables = [];
$this->subscribe();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$timeout = (int) $this->option('timeout');
if ($table = $this->option('table')) {
if (is_array($table)) {
$this->tables = $table;
} else {
$this->tables[] = $table;
}
}
try {
$dbo = DB::connection('DATABASE_NAME_HERE')->getPdo();
$dbo->exec('LISTEN "events"');
while (true) {
$event = $dbo->pgsqlGetNotify(\PDO::FETCH_ASSOC, $timeout * 1000);
if ($this->output->isDebug()) {
$this->getOutput()->write($event);
$this->getOutput()->write(PHP_EOL);
}
$payload = json_decode($event['payload']);
$table = $payload->table;
$action = $payload->action;
$original = $payload->original;
$data = $payload->data;
$observer = null;
$subject = implode('@', [$table, strtolower($action)]);
if (array_key_exists($subject, $this->subscribers)) {
$observer = $this->subscribers[$subject];
} else if (array_key_exists($table, $this->subscribers)) {
$observer = $this->subscribers[$table];
}
if (isset($observer) && method_exists($this, $observer->handler)) {
$handler = $observer->handler;
$this->$handler($data, $action, $original);
}
}
} catch (Exception $e) {
logger($e->getMessage());
}
}
/**
* Set up observers to handle events on a table.
*
* @param $entity
* @param $handler
*/
private function listen($entity, $handler)
{
if (!isset($this->subscribers)) {
$this->subscribers = [];
}
$info = explode('@', $entity);
$table = $info[0];
$action = count($info) > 1 ? $info[1] : null;
$observer = new \stdClass();
$observer->table = $table;
$observer->action = $action;
$observer->handler = $handler;
$subject = !empty($action) ? implode('@', [$table, strtolower($action)]) : $table;
$this->subscribers[$subject] = $observer;
}
/**
* Subscribe to modification events on these tables.
*/
private function subscribe()
{
$this->listen('orders_table', 'onOrder');
$this->listen('users_table', 'onUser');
}
/**
* @param $order
* @param null $action
* @param null $original
*/
protected function onOrder($order, $action = null, $original = null)
{
$event = null;
if ($action == 'INSERT') {
$event = new OrderCreated();
} else if ($action === 'UPDATE') {
$event = new OrderUpdated();
} else if ($action == 'DELETE') {
$event = new OrderDeleted();
}
if (!is_null($event)) {
event($event);
}
}
/**
* @param $user
* @param null $action
* @param null $original
*/
protected function onUser($user, $action = null, $original = null)
{
$event = null;
if ($action == 'INSERT') {
$event = new UserCreated();
} else if ($action === 'UPDATE') {
$event = new UserUpdated();
} else if ($action == 'DELETE') {
$event = new UserDeleted();
}
if (!is_null($event)) {
event($event);
}
}
}
然后您将编写一个 Laravel 订阅者来为命令中定义的每个事件定义 EventListener:
- OrderCreated / OrderUpdated / OrderDeleted
- 用户创建/用户更新/用户删除
并确保在 EventServiceProvider 的 $subscribers 块中注册此订阅者。
参考文献
PostgreSQL Triggers
PostgreSQL JSON and Functions
Laravel Events: Subscribers