muffin/sti

CakePHP ORM的单表继承

安装: 769

依赖项: 0

建议者: 0

安全: 0

星标: 6

关注者: 5

分支: 7

类型:cakephp-plugin

2.0.0-beta 2020-01-16 13:41 UTC

This package is auto-updated.

Last update: 2024-08-26 05:42:18 UTC


README

Build Status Coverage Total Downloads License

CakePHP ORM的单表继承。

[...] 这是一种在关系型数据库中模拟面向对象继承的方法。当将数据库表映射到面向对象语言中的对象时,数据库中的一个字段标识了对象属于继承层次中的哪个类。

(来源: 维基百科)

安装

使用 Composer

composer require muffin/sti

然后需要加载插件。您可以使用控制台命令

bin/cake plugin load Muffin/Sti

用法

<?php // src/Model/Table/CooksTable.php
namespace App\Model\Table;

use Cake\ORM\Table;

class CooksTable extends Table
{
    public function initialize($config)
    {
        $this->setTable('sti_cooks');
        $this->addBehavior('Muffin/Sti.Sti', [
            'typeMap' => [
                'chef' => 'App\Model\Entity\Chef',
                'baker' => 'App\Model\Entity\Baker',
                'assistant_chef' => 'App\Model\Entity\AssistantChef',
            ]
        ]);

        // Optionally, set the default type. If none is defined, the
        // first one (i.e. `chef`) will be used.
        $this->setEntityClass('App\Model\Entity\AssistantChef');
    }
}

然后为每种实体类型创建一个类

  • 厨师
  • 面包师
  • 助理厨师

之前定义为“默认”的实体需要使用 StiAwareTrait

<?php // src/Model/Entity/AssistantChef.php
namespace App\Model\Entity;

use Cake\ORM\Entity;
use Muffin\Sti\Model\Entity\StiAwareTrait;

class AssistantChef extends Entity
{
    use StiAwareTrait;
}

可选地,您可以为扩展父表的表创建类以封装业务逻辑

<?php // src/Model/Table/ChefsTable.php
namespace App\Model\Table;

class ChefsTable extends CooksTable
{
  // ...
}

我说的是可选的,因为如果您只需要一些额外的验证规则,您可以在父表上定义这些规则。例如,为厨师添加自定义规则

// src/Model/Table/CooksTable.php
public function validationChefs(Validator $validator)
{
    // ...
    return $validator;
}

新实体

该行为将自动添加创建不同类型实体(例如 newChef())的辅助方法。创建新实体有不同方式,所有方式都是有效的,根据情况,您可能需要一种或另一种

// using the parent table
$cooks->newChef([...]);

// or, using the parent table again
$cooks->newEntity(['type' => 'chef', ...]);

// or, using the child table
$chefs->newEntity([...]);

注意

为了使上面的示例使用 (*chef) 能够工作,您需要向 Inflector 添加自定义规则

Cake\Utility\Inflector::rules('plural', ['/chef$/i' => '\1Chefs']);

补丁和功能

  • 分支
  • 修改、修复
  • 测试 - 这很重要,所以不要无意中破坏它
  • 提交 - 不要修改许可、todo、版本等。(如果您更改了任何内容,请将其放入自己的提交中,这样我在拉取时可以忽略它们)
  • 拉取请求 - 主题分支的额外加分项

为了确保您的PR被考虑为上游,您必须遵循 CakePHP编码规范

错误和反馈

http://github.com/usemuffin/sti/issues

许可

版权所有(c)2015-现在,Use Muffin,许可协议为MIT许可协议