kenarkose/ownable

该包已废弃,不再维护。未建议替代包。

Laravel 5 上 Eloquent 模型的简单所有权

1.4.0 2016-08-07 10:40 UTC

This package is not auto-updated.

Last update: 2019-11-04 08:48:23 UTC


README

Laravel 5 上 Eloquent 模型的简单所有权。

Build Status Total Downloads Latest Stable Version License

Ownable 提供了一种简单的方法来将所有者(很可能是用户模型)关联到单个模型。

特性

  • 兼容 Laravel 5
  • 可配置
  • 创建时自动关联授权用户为所有者(Laravel 实现)
  • 更改所有者
  • Eloquent 关联
  • 提供用于轻松开发的 phpunit 测试套件

安装

安装 Ownable 非常简单。只需通过 Composer 拉取包。

{
    "require": {
        "kenarkose/ownable": "~1.0"
    }
}

使用方法

只需将特性添加到要成为所有权的模型中,并根据需要自定义。

use Illuminate\Database\Eloquent\Model;
use Kenarkose\Ownable\AutoAssociatesOwner;
use Kenarkose\Ownable\Ownable;
use Kenarkose\Ownable\Contract\Ownable as OwnableContract;

class OwnableItem extends Model implements OwnableContract {
    
    use Ownable, AutoAssociatesOwner;
    
}

$ownable = OwnableItem::find();

// You may access owner like so:
$owner = $ownable->getOwner();

// or, you may use the Eloquent relation and dynamic property:
$owner = $ownable->owner;
$ownerRelation = $ownable->owner();


$ownable = new OwnableItem;

// You may change and remove owner and persist like so:
$ownable->changeOwnerTo($owner);
$ownable->abandonOwner();

// or, if you would like to do these without saving the model you can use:
$ownable->associateOwner($owner);
$ownable->dissociateOwner();

// You may also verify and check owners
$ownable->hasOwner();
$ownable->isOwnedBy($owner);

AutoAssociatesOwner 特性是可选的,如果希望在模型创建时自动关联登录用户,则应使用该特性。换句话说,如果使用该特性,则模型将关联登录用户作为所有者。

自定义

您可以通过添加相关属性来自定义使用 Ownable 和 AutoAssociatesOwner 特性的单个模型。默认配置如下所示。

protected $ownerModel = 'App\User';
protected $ownerKey = 'user_id';
protected $ownerParentKey = 'id';

所有这些属性都是可选的,如果未设置,则回退到默认值。

最后,如果您想更改默认的自动关联行为,您可以通过重写 associateDefaultOwner 方法来实现。

use Illuminate\Database\Eloquent\Model;
use Kenarkose\Ownable\Ownable;
use Kenarkose\Ownable\AutoAssociatesOwner;
use Kenarkose\Ownable\Contract\Ownable as OwnableContract;

class OwnableItem extends Model implements OwnableContract {
    
    use Ownable, AutoAssociatesOwner;
    
    public function associateDefaultOwner()
    {
        // Some other logic
    }
}

许可

Ownable 在 MIT 许可证 下发布。