All Projects → jlorente → yii2-activerecord-inheritance

jlorente / yii2-activerecord-inheritance

Licence: MIT license
ActiveRecord Inheritance is an util to provide the Class Table Inheritance Pattern the to the Yii2 framework

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to yii2-activerecord-inheritance

Ooor
Odoo Ruby JSON client. Emulates ActiveRecord enough (as much as Mongoid; Implements ActiveModel) to make Rails development with an Odoo datastore straightforward
Stars: ✭ 184 (+922.22%)
Mutual labels:  activerecord
Activerecord json validator
🔩 ActiveRecord::JSONValidator makes it easy to validate JSON attributes against a JSON schema.
Stars: ✭ 220 (+1122.22%)
Mutual labels:  activerecord
n1 loader
Loader to solve N+1 issues for good. Highly recommended for GraphQL API.
Stars: ✭ 182 (+911.11%)
Mutual labels:  activerecord
Ar Softdelete
Soft delete behavior for ActiveRecord
Stars: ✭ 188 (+944.44%)
Mutual labels:  activerecord
Anima
Minimal database operation library.
Stars: ✭ 210 (+1066.67%)
Mutual labels:  activerecord
Octopus
Database Sharding for ActiveRecord
Stars: ✭ 2,496 (+13766.67%)
Mutual labels:  activerecord
Activejpa
A simple active record pattern library in java that makes programming DAL easier
Stars: ✭ 172 (+855.56%)
Mutual labels:  activerecord
sql-builder
A simple SQL builder for generate SQL for non-ActiveRecord supports databases
Stars: ✭ 34 (+88.89%)
Mutual labels:  activerecord
Secondbase
Seamless second database integration for Rails.
Stars: ✭ 216 (+1100%)
Mutual labels:  activerecord
Scenic
Scenic is maintained by Derek Prior, Caleb Hearth, and you, our contributors.
Stars: ✭ 2,856 (+15766.67%)
Mutual labels:  activerecord
Jsonapi Utils
Build JSON API-compliant APIs on Rails with no (or less) learning curve.
Stars: ✭ 191 (+961.11%)
Mutual labels:  activerecord
Randumb
Adds ability to pull back random records from Active Record
Stars: ✭ 208 (+1055.56%)
Mutual labels:  activerecord
Activerecord Postgres enum
Integrate PostgreSQL's enum data type into ActiveRecord's schema and migrations.
Stars: ✭ 227 (+1161.11%)
Mutual labels:  activerecord
Groupify
Add group and membership functionality to your Rails models
Stars: ✭ 187 (+938.89%)
Mutual labels:  activerecord
query-objects-example
Example of rails app using Query Objects
Stars: ✭ 37 (+105.56%)
Mutual labels:  activerecord
Ldaprecord Laravel
Multi-domain LDAP Authentication & Management for Laravel.
Stars: ✭ 178 (+888.89%)
Mutual labels:  activerecord
Seamless database pool
Add support for master/slave database clusters in ActiveRecord to improve performance.
Stars: ✭ 222 (+1133.33%)
Mutual labels:  activerecord
embedded
Rails/Activerecord plugin to make value objects embedded into active record objects
Stars: ✭ 48 (+166.67%)
Mutual labels:  activerecord
activerecord-migrations
A gem to simplify activerecord migrations in non-rails projects.
Stars: ✭ 15 (-16.67%)
Mutual labels:  activerecord
Occams Record
The missing high-efficiency query API for ActiveRecord
Stars: ✭ 240 (+1233.33%)
Mutual labels:  activerecord

ActiveRecord Inheritance

ActiveRecord Inheritance is a util to provide the Class Table Inheritance Pattern to the Yii2 framework. Its motivation is to fake inheritance between two ActiveRecord classes.

Installation

Include the package as dependency under the bower.json file.

To install, either run

$ php composer.phar require jlorente/yii2-activerecord-inheritance "*"

or add

...
    "require": {
        ...
        "jlorente/yii2-activerecord-inheritance": "*"
    }

to the require section of your composer.json file.

Usage

An example of usage could be:

Suppose you have the following schema.

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `last_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` int(11) NOT NULL,
  `updated_at` int(11) NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `admin` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `level` INT NOT NULL,
  `banned_users` INT NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  CONSTRAINT `FK_Admin_Id` FOREIGN KEY (`id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
);

To fake the inheritance between the two tables your code must look like this.

use jlorente\db\ActiveRecordInheritanceTrait,
    jlorente\db\ActiveRecordInheritanceInterface;
use yii\db\ActiveRecord;

class User extends ActiveRecord {

    public function tableName() {
        return 'user';
    }

    public function doSomething() {
        echo 'User does something';
    }
}

class Admin extends ActiveRecord implements ActiveRecordInheritanceInterface {
    use ActiveRecordInheritanceTrait;

    public function tableName() {
        return 'admin';
    }

    public static function extendsFrom() {
        return User::className();
    }

    public function doSomething() {
        echo 'Admin does something';
    }
}

And you will be able to use Admin objects as if they were inheriting from User objects.

$admin = new Admin();
$admin->username = 'al-acran';
$admin->email = '[email protected]';
$admin->name = 'Al';
$admin->last_name = 'Acran';
$admin->level = 1;
$admin->save();

You can call parent methods and properties by using the parent relation property.

$admin->doSomething()           //Admin does something
$admin->parent->doSomething()   //User does something

This trait is very useful for faking inheritance, however query filters should be applied on the parent relation.

$admin = Admin::find()
    ->joinWith('parent', function($query) {
        $query->andWhere(['username' => 'al-acran']);
        $query->andWhere(['name' => 'Al']);
    })
    ->andWhere(['level' => 1])
    ->one();

Considerations

In order to use the trait properly, you must consider the following points

General

  • By default, the primary key of the supposed child class is used as foreign key of the parent model, if you want to use another attribute as foreign key, yoy should overwrite the parentAttribute() method.
  • The trait won't work with multiple primary and foreign keys.

ActiveRecord methods

  • Methods overwriten from ActiveRecord in this trait like save, validate, etc... should not be overwriten on the class that uses the trait or functionality will be lost.
  • To overwrite this methods properly, you could extend the class that uses the trait and overwrite there the methods, making sure that all methods call its parent implementation.

Inheritance call hierarchy

  • The natural call hierarchy is preserved, so if a method or property exists on the called class or one of its ancestors, the method or property is called.
  • If a method or property doesn't exist in the natural call hierarchy. The properly magic method is called (__get, __set, __isset, __unset, __call) and the yii2 call hierarchy is used. If the method or property isn't found in this call hierarchy the next step is executed.
  • The previous process is repeteated for the faked parent object.
  • The call hierarchy will stop when a method or property is found or when there are no more parents. In this case, an UnknownPropertyException or an UnknownMethodException will be raised.
  • You can concatenate faked parent classes with the only limit of the php call stack.

License

Copyright © 2015 José Lorente Martín [email protected]. Licensed under the MIT license. See LICENSE.txt for details.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].