sam-it / yii2-singletableinheritance
Single Table Inheritance for Yii2
Installs: 15 498
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 10
Requires
- php: > 7.4
Requires (Dev)
- brainmaestro/composer-git-hooks: ^2.8
- phpunit/phpunit: ^9.1
- squizlabs/php_codesniffer: ^3.5
- dev-master
- v2.0.1
- v2.0.0
- v1.0.1
- v1.0.0
- dev-dependabot/npm_and_yarn/node-fetch-2.6.7
- dev-dependabot/npm_and_yarn/semantic-release-19.0.3
- dev-dependabot/npm_and_yarn/minimist-1.2.6
- dev-dependabot/npm_and_yarn/path-parse-1.0.7
- dev-dependabot/npm_and_yarn/glob-parent-5.1.2
- dev-dependabot/npm_and_yarn/normalize-url-5.3.1
- dev-dependabot/npm_and_yarn/hosted-git-info-2.8.9
- dev-dependabot/npm_and_yarn/handlebars-4.7.7
- dev-dependabot/npm_and_yarn/y18n-4.0.1
- dev-dependabot/npm_and_yarn/ini-1.3.8
This package is auto-updated.
Last update: 2024-10-25 17:50:03 UTC
README
Yii2 Single Table Inheritance (STI) using traits
The reason this is implemented as traits is to prevent developers from putting 3rd party classes in their class hierarchy. This implementation uses 2 traits, 1 for the query class and 1 for the model class.
The query trait adds a filter based on the model class configured for the query. It implements the prepare()
function.
In case you use this trait on a class that also implements the prepare()
function you MUST manually call ours like this:
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); } }
The model trait is a bit more complicated but still has a small surface of interaction with your code. It uses the init()
function, so if you override that in the base STI class (the one where you use the trait) you must call our init function:
class Transport extends \yii\db\ActiveRecord { use \SamIT\Yii2\SingleTableInheritance\SingleTableInheritanceTrait; public function init(): void { self::initSingleTableInheritance($this); } }
Configure your inheritance config by implementing a static function:
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' ] ]; } }
This function is only called once and its results are cached.