iconic/engine

引擎是一个工作流程状态机,有助于将业务逻辑集中化

v0.1.9 2020-12-08 09:08 UTC

This package is auto-updated.

Last update: 2024-09-27 15:13:02 UTC


README

引擎深受symfony/workflow的启发,但旨在使用更加简单,并允许对工作流程转换和动作的执行者以及对象的额外检查。

安装

您可以使用composer安装此库

composer require iconic/engine

快速指南

您只需创建一个Engine实例,并开始定义和检查属性和执行者上的允许动作(支持getter/setter和公共属性)。

  • 允许所有人查看
$engine = new \Iconic\Engine\Engine();
$engine->allow('view');
$allowed = $engine->can('view'); //returns true
$allowed = $engine->can('edit'); //returns false
  • 只有在帖子状态为草稿时才允许发布帖子
$post = new Post();
$post->status = "submitted";
$engine = new \Iconic\Engine\Engine();

$engine->allow('publish')->of('status', 'draft', 'published');

$allowed = $engine->can('publish', $post); //returns false
$engine->apply('publish', $post); //throws Exception

$post->status = "draft";
$allowed = $engine->can('publish', $post); //returns true
$engine->apply('publish', $post); //changes post status to "published"
  • 仅允许具有"editor"角色的执行者编辑,无需定义对象限制
$user = new User();
$user->role = "user";

$engine = new \Iconic\Engine\Engine();
$engine->allow('edit')->if('role', 'editor');
$allowed = $engine->can('edit', null, $user); //returns false
  • 结合上述两种情况。允许具有"status" "draft"状态的帖子被具有"role" "editor"角色的执行者发布
$editor = new User();
$editor->role = 'editor';
$user = new User();
$user->role = 'user';
$draftPost = new Post();
$draftPost->status = "draft";
$deletedPost = new Post();
$deletedPost->status = "deleted";

$engine = new \Iconic\Engine\Engine();
$engine->allow('publish')->of('status', 'draft', 'published');
$engine->allow('publish')->if('role', 'editor');

$engine->can('publish', $draftPost, $editor); //returns true
$engine->apply('publish', $draftPost, $editor); //changes post status to "published"

$engine->can('publish', $deletedPost, $editor); //returns false
$engine->apply('publish', $deletedPost, $editor); //throws exception
$engine->can('publish', $draftPost, $user); //returns false  
$engine->apply('publish', $draftPost, $user); //throws exception  
  • 您可以为每个动作定义多个规则