松饼 / 足迹
CakePHP 插件,允许将当前登录用户传递到模型层
Requires
- cakephp/cakephp: ^5.0
Requires (Dev)
- cakephp/cakephp-codesniffer: ^5.0
- phpunit/phpunit: ^10.1
README
此插件允许您将当前登录用户信息传递到 CakePHP 应用程序的模型层。
它包含 FootprintBehavior
,允许您控制类似 user_id
、created_by
、company_id
的列,类似于核心的 TimestampBehavior
。
安装
使用 Composer
composer require muffin/footprint
然后您需要运行控制台命令来加载插件
bin/cake plugin load Muffin/Footprint
足迹插件必须在 Authentication 插件之前加载,因此您应该相应地更新您的 config/plugins.php
或 Application::bootstrap()
。
使用方法
中间件
将 FootprintMiddleware
添加到您的 Application::middleware()
方法中的中间件队列
$middleware->add('Muffin/Footprint.Footprint');
它必须在 AuthenticationMiddleware
之后添加,以确保在认证完成后可以读取身份信息。
如果您没有直接访问 AuthenticationMiddleware
被添加的地方,请查看此处。
行为
例如,要使用包含的行为自动更新记录的 created_by
和 modified_by
字段,请将以下内容添加到您的表的 initialize()
方法中
$this->addBehavior('Muffin/Footprint.Footprint');
您可以像这样进行自定义
$this->addBehavior('Muffin/Footprint.Footprint', [ 'events' => [ 'Model.beforeSave' => [ 'user_id' => 'new', 'company_id' => 'new', 'modified_by' => 'always' ] ], 'propertiesMap' => [ 'company_id' => '_footprint.company.id', ], ]);
这将插入当前登录用户的主键到 user_id
和 modified_by
字段中,在更新记录时再次在 modified_by
字段中插入,并在创建记录时使用相关用户记录的公司 id
在 company_id
字段中。
您还可以提供一个接受 EntityInterface 并返回 bool 的闭包
$this->addBehavior('Muffin/Footprint.Footprint', [ 'events' => [ 'Model.beforeSave' => [ 'user_id' => 'new', 'company_id' => 'new', 'modified_by' => 'always', 'deleted_by' => function ($entity): bool { return $entity->deleted !== null; }, ] ], ]);
通过事件添加中间件
在某些情况下,您没有直接访问 AuthenticationMiddleware
被添加的地方。然后您将需要在您的 src/Application.php
中添加以下内容
use Authentication\Middleware\AuthenticationMiddleware; use Cake\Event\EventInterface; use Cake\Http\MiddlewareQueue; use Muffin\Footprint\Middleware\FootprintMiddleware; // inside the bootstrap() method $this->getEventManager()->on( 'Server.buildMiddleware', function (EventInterface $event, MiddlewareQueue $middleware) { $middleware->insertAfter(AuthenticationMiddleware::class, FootprintMiddleware::class); } );
补丁 & 功能
- 分支
- 修改,修复
- 测试 - 这很重要,所以它不会无意中损坏
- 提交 - 不要修改许可,todo,版本等。(如果您更改了任何内容,请将它们提升到自己的提交中,这样我在拉取时可以忽略它们)
- 拉取请求 - 主题分支的加分项
错误 & 反馈
http://github.com/usemuffin/footprint/issues
许可
版权 (c) 2015-现在,Use Muffin,并许可于 The MIT License。