sota2501/cakephp-ownership

CakePHP的所有权插件

安装: 203

依赖项: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 0

开放问题: 0

类型:cakephp-plugin

2.0.1 2024-04-04 14:53 UTC

This package is auto-updated.

Last update: 2024-09-07 18:11:09 UTC


README

所有权插件是一个设计用来引入所有权功能的插件(与用户功能区分开来)。关键区别在于确保实体的所有者与关联实体的所有者匹配。然而,需要注意的是,保证这种所有权匹配可能会导致SELECT执行次数增加。

安装

您可以使用 composer 将此插件安装到您的CakePHP应用程序中。

安装composer包的推荐方法是

composer require sota2501/cakephp-ownership

在您的项目中的 src/Application.php 文件中添加以下语句来加载插件

public function bootstrap(): void
{
    parent::bootstrap();

    $this->addPlugin('Ownership');
}

所有权设置

您必须在 OwnersTable 中实现 OwnersTableInterface(例如:UsersTable)。下面是一个示例,但可以按照原样实现。

use Ownership\Model\Table\OwnersTableInterface;

class UsersTable extends Table implements OwnersTableInterface
{
    protected $currentEntity = null;

    public function getCurrentEntity(): ?EntityInterface
    {
        return $this->currentEntity;
    }

    public function setCurrentEntity(?EntityInterface $entity): void
    {
        $this->currentEntity = $entity;
    }
}

至少,您必须将 OwnershipBehavior 添加到引入所有权的表中(不需要添加到所有者模型或未引入所有权的模型)。对于选项,在 'owner' 中指定所有者模型名称,在 'parent' 中指定到所有者模型的关联键名称。

// ex) ArticleItemsTable => Articles => ( ... => ) Users
class ArticleItemsTable extends Table
{
    public function initialize(array $config): void
    {
        // ...
        $this->addBehavior('Ownership.Ownership', ['owner' => 'Users', 'parent' => 'Articles']);

        $this->belongsTo('Articles', [
            'foreignKey' => 'article_id',
        ]);
        // ...
    }
}

在不引入所有权的情况下,您可以不指定任何选项来添加 OwnershipBehavior。

用法

此插件提供的一致性保证自动在 beforeSave 事件中执行,不提供避免此行为的方法。

此插件提供了一个查找器,用于获取特定用户拥有的实体。此外,它还提供了一个查找器,用于获取即使引入了所有权,也不是所有者拥有的实体。

$article = $articles->find('owned', ['owner_id' => 1])->first();
$article = $articles->find('nonOwned')->first();

通过使用所有者模型中实现的方法,特别是通过设置已登录的用户,您可以获取仅由当前登录用户拥有的实体,而无需指定 owner_id。请注意,至少必须指定其中之一,但如果两者都指定,则 owner_id 优先。

除了上述功能外,OwnershipBehavior还提供了两个函数

$id = $articles->getOwnerId($article);
$isConsistent = $articles->isOwnerConsistent($article);

第一个函数以数组的形式获取所有者的ID [field_name => ID]。如果实体未拥有所有者,则返回 null;如果没有引入所有权,则返回 false。

第二个函数用于检查所有者的一致性。

许可证

所有权插件受MIT许可证许可。