Skip to content

Instantly share code, notes, and snippets.

@renan
Last active August 29, 2015 14:05
Show Gist options
  • Save renan/b017c844bc03e0b27711 to your computer and use it in GitHub Desktop.
Save renan/b017c844bc03e0b27711 to your computer and use it in GitHub Desktop.
<?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