Last active
August 29, 2015 14:05
-
-
Save renan/b017c844bc03e0b27711 to your computer and use it in GitHub Desktop.
This file contains 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 | |
namespace App\Model; | |
use Cake\ORM\TableRegistry; | |
use Cake\Utility\Inflector; | |
trait ActiveRecordTrait { | |
protected static $overrideMethodMap = [ | |
'fetch' => 'get', | |
]; | |
protected static $cachedRepositoryMap = []; | |
public static function rewireSource($newSource) { | |
$calledClass = get_called_class(); | |
static::$cachedRepositoryMap[$calledClass] = $newSource; | |
} | |
public static function __callStatic($method, $arguments) { | |
$calledClass = get_called_class(); | |
if (isset(static::$cachedRepositoryMap[$calledClass])) { | |
$tableClass = static::$cachedRepositoryMap[$calledClass]; | |
} else { | |
$tableClass = str_replace('App\\Model\\Entity\\', '', $calledClass); | |
$tableClass = Inflector::tableize($tableClass); | |
static::$cachedRepositoryMap[$calledClass] = $tableClass; | |
} | |
if (isset(static::$overrideMethodMap[$method])) { | |
$method = static::$overrideMethodMap[$method]; | |
} | |
$table = TableRegistry::get($tableClass); | |
if (!method_exists($table, $method)) { | |
throw new \BadMethodCallException('Invalid method ' . $method); | |
} | |
return call_user_func_array([$table, $method], $arguments); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment