Subscribe MySQL events like jQuery, base on php-mysql-replication
In your MySQL server configuration file you need to enable replication:
[mysqld]
server-id = 1
log_bin = /var/log/mysql/mysql-bin.log
expire_logs_days = 10
max_binlog_size = 100M
binlog_row_image = full
binlog-format = row #Very important if you want to receive write, update and delete row events
Mysql replication events explained https://dev.mysql.com/doc/internals/en/event-meanings.html
Mysql user privileges:
GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'user'@'host';
GRANT SELECT ON `dbName`.* TO 'user'@'host';
install
composer require "huangdijia/laravel-trigger:^4.0"
publish config
php artisan vendor:publish --provider="Huangdijia\Trigger\TriggerServiceProvider"
install
composer require "huangdijia/laravel-trigger:^4.0"
edit bootstrap/app.php
add:
$app->register(Huangdijia\Trigger\TriggerServiceProvider::class);
...
$app->configure('trigger');
publish config and route
php artisan trigger:install [--force]
edit .env
, add:
TRIGGER_HOST=192.168.xxx.xxx
TRIGGER_PORT=3306
TRIGGER_USER=username
TRIGGER_PASSWORD=password
...
php artisan trigger:start [-R=xxx]
<?php
namespace App\Listeners;
use Huangdijia\Trigger\EventSubscriber;
class ExampeSubscriber extends EventSubscriber
{
public function onUpdate(UpdateRowsDTO $event)
{
//
}
public function onDelete(DeleteRowsDTO $event)
{
//
}
public function onWrite(WriteRowsDTO $event)
{
//
}
}
more subscriber usage
$trigger->on('database.table', 'write', function($event) { /* do something */ });
$trigger->on('database.table1,database.table2', 'write,update', function($event) { /* do something */ });
$trigger->on('database.table1,database.table2', [
'write' => function($event) { /* do something */ },
'update' => function($event) { /* do something */ },
]);
$trigger->on('database.table', 'write', 'App\\Http\\Controllers\\ExampleController'); // call default method 'handle'
$trigger->on('database.table', 'write', 'App\\Http\\Controllers\\ExampleController@write');
class Foo
{
public static function bar($event)
{
dump($event);
}
}
$trigger->on('database.table', 'write', 'Foo@bar'); // call default method 'handle'
$trigger->on('database.table', 'write', ['Foo', 'bar']);
Job
namespace App\Jobs;
class ExampleJob extends Job
{
private $event;
public function __construct($event)
{
$this->event = $event;
}
public function handle()
{
dump($this->event);
}
}
Route
$trigger->on('database.table', 'write', 'App\Jobs\ExampleJob'); // call default method 'dispatch'
$trigger->on('database.table', 'write', 'App\Jobs\ExampleJob@dispatch_now');
php artisan trigger:list [-R=xxx]
php artisan trigger:terminate [-R=xxx]