sam-it/yii2-singletableinheritance

为 Yii2 实现的单表继承


README

Scrutinizer Code Quality Code Coverage Continous integration Latest Stable Version Total Downloads License Monthly Downloads

使用 traits 实现的 Yii2 单表继承 (STI)

将此实现为 traits 的原因是为了防止开发者在类层次结构中放入第三方类。此实现使用了两个 traits,一个用于查询类,一个用于模型类。

查询 trait 基于为查询配置的模型类添加过滤器。它实现了 prepare() 函数。如果你在也实现了 prepare() 函数的类上使用此 trait,你必须手动调用我们的,如下所示

class MyQuery extends \yii\db\ActiveQuery 
{
    use \SamIT\Yii2\SingleTableInheritance\SingleTableInheritanceQueryTrait;

    public function prepare($builder) 
    {
        // Your own code here
        $this->prepareSingleTableInheritance();
        // Your own code here
        return parent::prepare($builder);
    }
}

模型 trait 稍微复杂一些,但仍然与你的代码有少量交互。它使用 init() 函数,因此如果你在基础 STI 类(你使用 traits 的那个类)中重写了它,你必须调用我们的 init 函数

class Transport extends \yii\db\ActiveRecord 
{
    use \SamIT\Yii2\SingleTableInheritance\SingleTableInheritanceTrait;
    public function init(): void 
    {
        self::initSingleTableInheritance($this);
    } 
}

通过实现一个静态函数来配置你的继承配置

class Transport extends \yii\db\ActiveRecord 
{
    use \SamIT\Yii2\SingleTableInheritance\SingleTableInheritanceTrait;
    private static function inheritanceConfig(): array
    {
        return [
            'column' => 'type',
            'map' => [
                Car::class => 'car',
                Bike::class => 'bike'
            ]    
        ];       
    }
}

此函数只调用一次,其结果被缓存。