mpyw / laravel-transaction-observer
此包已被废弃,不再维护。未建议替代包。
监听延迟事件,并在所有事务完成后触发它们。
此包尚未发布版本,信息不多。
README
监听延迟事件,并在所有事务完成后触发它们。
要求
- PHP: ^5.5 || ^7.0
- Laravel: ^5.4
安装
composer require mpyw/laravel-transaction-observer:^1.0
基本用法
注册服务提供者。
config/app.php
:
/* * Package Service Providers... */ mpyw\LaravelTransactionObserver\Provider::class,
就这么多。现在你可以分发以回调作为第一个参数的 DelayedCall
。
public mpyw\LaravelTransactionObserver\Events\DelayedCall::__construct(callable $callback) public void mpyw\LaravelTransactionObserver\Events\DelayedCall::fire()
注意,回调是
- 在所有事务完成后触发的。
- 如果当前事务失败则取消。
/** * Example: Handling callbacks for counter caching */ use mpyw\LaravelTransactionObserver\Events\DelayedCall; DB::transaction(function () { $post = Post::create([ 'text' => 'This is main text', 'comment_count' => 0, ]); DB::transaction(function () use ($post) { $comment = new Comment(['text' => 'This is first comment']); $comment->post()->associate($post); $comment->save(); event(new DelayedCall(function () use ($post) { ++$post->comment_count; // A: Increment counter cache! })); }); DB::transaction(function () use ($post) { $comment = new Comment(['text' => 'This is second comment']); $comment->post()->associate($post); $comment->save(); event(new DelayedCall(function () use ($post) { ++$post->comment_count; // B: Increment counter cache! })); throw new \RuntimeException('Oops!'); }); }); // A fires here, while B never do.
高级用法:准备自定义事件类
1. 创建一个实现 DelayedEvent
的类。
app/Events/MyDelayedEvent.php
:
<?php namespace App\Events; use mpyw\LaravelTransactionObserver\Contracts\DelayedEvent; class MyDelayedEvent implements DelayedEvent { protected $payload; public function __construct($payload) { $this->payload = $payload; } public function fire() { ($this->payload)(); } }
2. 在你的应用程序服务提供者中监听它。
app/Providers/AppServiceProvider.php
:
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use mpyw\LaravelTransactionObserver\Facades\TransactionObserver; use App\Events\MyDelayedEvent; class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { // } /** * Bootstrap any application services. * * @return void */ public function boot() { TransactionObserver::listen(MyDelayedEvent::class); } }
相关包
- mpyw/laravel-delayed-counter-cache: 延迟计数器缓存,在事务外递增/递减