nanigans/single-table-inheritance
Composer 安装命令:
composer require nanigans/single-table-inheritance
包简介
Single Table Inheritance Trait
README 文档
README
Single Table Inheritance is a trait for Laravel 5.8+ Eloquent models that allows multiple models to be stored in the same database table. We support a few key features
- Implemented as a Trait so that it plays nice with others, such as Laravel's
SoftDeletingTraitor the excellent Validating, without requiring a complicated mess of Eloquent Model subclasses. - Allow arbitrary class hierarchies not just two-level parent-child relationships.
- Customizable database column name that is used to store the model type.
- Customizable string for the model type value stored in the database. (As opposed to forcing the use of the fully qualified model class name.)
- Allow database rows that don't map to known model types. They will never be returned in queries.
Installation
Simply add the package to your composer.json file and run composer update.
"nanigans/single-table-inheritance": "~1.0"
Or go to your project directory where the composer.json file is located and type:
composer require "nanigans/single-table-inheritance:~1.0"
Overview
Getting started with the Single Table Inheritance Trait is simple. Add the constraint and add a few properties to your models. A complete example of a Vehicle super class with two subclasses Truck and Car is given by
use Nanigans\SingleTableInheritance\SingleTableInheritanceTrait; class Vehicle extends Model { use SingleTableInheritanceTrait; protected $table = "vehicles"; protected static $singleTableTypeField = 'type'; protected static $singleTableSubclasses = [Car::class, Truck::class]; } class Car extends Vehicle { protected static $singleTableType = 'car'; } class Truck extends Vehicle { protected static $singleTableType = 'truck'; }
There are four required properties to be defined in your classes:
Define the database table
In the root model set the protected property $table to define which database table to use to store all your classes.
Note: even if you are using the default for the root class (i.e. the 'vehicles' table for the Vehicle class) this is required so that subclasses inherit the same setting rather than defaulting to their own table name.
Define the database column to store the class type
In the root model set the protected static property $singleTableTypeField to define which database column to use to store the type of each class.
Define the subclasses
In the root model and each branch model define the protected static property $singleTableSubclasses to define which subclasses are part of the classes hierarchy.
Define the values for class type
In each concrete class set the protected static property $singleTableType to define the string value for this class that will be stored in the $singleTableTypeField database column.
Multi Level Class Hierarchies
It's not uncommon to have many levels in your class hierarchy. Its easy to define that structure by declaring subclasses at each level. For example suppose you have a Vehicle super class with two subclasses Bike and MotorVehicle. MotorVehicle in trun has two subclasses Car and Truck. You would define the classes like this:
use Nanigans\SingleTableInheritance\SingleTableInheritanceTrait; class Vehicle extends Model { use SingleTableInheritanceTrait; protected $table = "vehicles"; protected static $singleTableTypeField = 'type'; protected static $singleTableSubclasses = [MotorVehicle::class, Bike::class]; } class MotorVehicle extends Vehicle { protected static $singleTableSubclasses = [Car::class, Truck::class]; } class Car extends MotorVehicle { protected static $singleTableType = 'car'; } class Truck extends MotorVehicle { protected static $singleTableType = 'truck'; } class Bike extends Vehicle { protected static $singleTableType = 'bike'; }
Defining Which Attributes Are Persisted
Eloquent is extremely lenient in allowing you to get and set attributes. There is no mechanism to declare the set of attributes that a model supports. If you misuse and attribute it typically results in a SQL error if you try to issue an insert or update for a column that doesn't exist. By default the SingleTableInheritanceTrait operates the same way. However, when storing a class hierarchy in a single table there are often database columns that don't apply to all classes in the hierarchy. That Eloquent will store values in those columns makes it considerably easier to write bugs. There, the SingleTableInheritanceTrait allows you to define which attributes are persisted. The set of persisted attributes is also inherited from parent classes.
class Vehicle extends Model { protected static $persisted = ['color'] } class MotorVehicle extends Vehicle { protected static $persisted = ['fuel'] }
In the above example the class Vehicle would persist the attribute color and the class MotorVehicle would persist both color and fuel.
Automatically Persisted Attributes
For convenience the model primary key and any dates are automatically added to the list of persisted attributes.
BelongsTo Relations
If you are restricting the persisted attribute and your model has BelongsTo relations then you must include the foreign key column of the BelongsTo relation. For example:
class Vehicle extends Model { protected static $persisted = ['color', 'owner_id']; public function owner() { return $this->belongsTo('User', 'owner_id'); } }
Unfortunately there is no efficient way to automatically detect BelongsTo foreign keys.
Throwing Exceptions for Invalid Attributes
BY default the SingleTableInheritanceTrait will handle invalid attributes silently It ignores non-persisted attributes when a model is saved and ignores non-persisted columns when hydrating a model from a builder query. However, you can force exceptions to be thrown when invalid attributes are encountered in either situation by setting the $throwInvalidAttributeExceptions property to true.
/** * Whether the model should throw an InvalidAttributesException if non-persisted * attributes are encountered when saving or hydrating a model. * If not set, it will default to false. * * @var boolean */ protected static $throwInvalidAttributeExceptions = true;
Inspiration
We've chosen a very particular implementation to support single table inheritance. However, others have written code and articles around a general approach that proved influential.
First, Mark Smith has an excellent article (no long live but available in web archive) Single Table Inheritance in Laravel 4 amongst other things is introduces the importance of queries returning objects of the correct type. Second, Jacopo Beschi wrote and extension of Eloquent's Model, Laravel-Single-Table-Inheritance`, that introduces the importance of being able to define which attributes each model persists.
The use of Traits was heavy influence by the Eloquent's SoftDeletingTrait and the excellent Validating Trait.
nanigans/single-table-inheritance 适用场景与选型建议
nanigans/single-table-inheritance 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.63M 次下载、GitHub Stars 达 251, 最近一次更新时间为 2014 年 09 月 15 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「model」 「laravel」 「inheritance」 「table」 「eloquent」 「single」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 nanigans/single-table-inheritance 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 nanigans/single-table-inheritance 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 nanigans/single-table-inheritance 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Symfony bundle which allows to override entities by using inheritance
Single Table Inheritance Trait
A package for automatically encrypting and decrypting Eloquent attributes in Laravel 5.5+, based on configuration settings.
Lightweight MTI (Multi-Table Inheritance) support for Eloquent models
Interfaces for web resource models and services to retrieve and create them
Laravel 5 - Repositories to the database layer
统计信息
- 总下载量: 2.63M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 251
- 点击次数: 22
- 依赖项目数: 3
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2014-09-15