acacha / stateful-eloquent
Eloquent类状态机
0.1.8
2017-05-11 18:51 UTC
Requires
- php: >=5.6.4
- laravel/framework: ~5.3
Requires (Dev)
- phpunit/phpunit: ^4.8
README
如果您熟悉我的AASM,那么这与此类似——只是在Laravel 5中用于Eloquent类。
参考
从https://github.com/mikerice/stateful-eloquent分叉而来
安装
步骤 1: 通过Composer安装
composer require acacha/stateful-eloquent
步骤 2: 添加服务提供者
Acacha\Stateful\Providers\StatefulServiceProvider::class,
步骤 3: 更新您的Eloquent模型
您的模型应该使用Stateful特性和接口
use Acacha\Stateful\Traits\StatefulTrait; use Acacha\Stateful\Contracts\Stateful; class Transaction extends Model implements Stateful { use StatefulTrait; }
步骤 4: 创建您的模型状态
您的模型应该有一个名为$states
的数组,用于定义模型状态。
/** * Transaction States * * @var array */ protected $states = [ 'draft' => ['initial' => true], 'processing', 'errored', 'active', 'closed' => ['final' => true] ];
步骤 5: 创建您的模型状态转换
/** * Transaction State Transitions * * @var array */ protected $transitions = [ 'process' => [ 'from' => ['draft', 'errored'], 'to' => 'processing' ], 'activate' => [ 'from' => 'processing', 'to' => 'active' ], 'fail' => [ 'from' => 'processing', 'to' => 'errored' ], 'close' => [ 'from' => 'active', 'to' => 'close' ] ]; /** * @return bool */ protected function validateProcess() { $validate = true; if (!$validate) { $this->addValidateProcessMessage(); } return $validate; } /** * @return bool */ protected function validateActivate() { //dd("validateActivate"); return true; } /** * @return bool */ protected function validateFail() { //dd("validateFail"); return true; } /** * @return bool */ protected function validateClose() { //dd("validateClose"); return true; } protected function beforeProcess() { //dd("doing something before entering processing state"); } protected function afterProcess() { //dd("doing something after leaving processing state"); }
数据库配置
您的模型迁移应该有一个状态字段,如下所示
class CreateModelTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('model', function (Blueprint $table) { $table->increments('id'); ... $table->string('state'); ... $table->timestamps(); }); }
用法
$transaction = new Transaction(); //Execute transition $transaction->process(); //Check if a state is active (return true or false) $transaction->active();