Created
January 23, 2014 11:51
-
-
Save danharper/8577330 to your computer and use it in GitHub Desktop.
Laravel/Eloquent Single Table Inheritance Trait
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Category extends Eloquent { | |
use EloquentSingleTableInheritenceTrait; | |
protected function singleTableInheritanceMpa() | |
{ | |
return [ | |
1 => 'InventoryCategory', | |
2 => 'PhotoCategory', | |
3 => 'BrochureCategory', | |
]; | |
} | |
} | |
class InventoryCategory extends Category { | |
} | |
class PhotoCategory extends Category { | |
} | |
class BrochureCategory extends Category { | |
} | |
// usage: | |
$product->category_id; // 1 | |
$product->category; // InventoryCategory | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// EloquentSingleTableInheritenceTrait.php | |
<?php | |
trait EloquentSingleTableInheritenceTrait { | |
protected function singleTableInheritanceKey() | |
{ | |
return 'id'; | |
} | |
protected function singleTableInheritanceMap() | |
{ | |
return []; | |
} | |
public function newFromBuilder($attributes = array()) | |
{ | |
$inheritanceKey = $this->singleTableInheritanceKey(); | |
$inheritanceMap = $this->singleTableInheritanceMap(); | |
$key = $attributes->$inheritanceKey; | |
if (array_key_exists($key, $inheritanceMap)) | |
{ | |
$instance = (new $inheritanceMap[$key])->newInstance([], true); | |
$instance->setRawAttributes((array) $attributes, true); | |
return $instance; | |
} | |
return parent::newFromBuilder($attributes); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment