Skip to content

Instantly share code, notes, and snippets.

@sorora
Last active December 31, 2015 20:38
Show Gist options
  • Save sorora/8041074 to your computer and use it in GitHub Desktop.
Save sorora/8041074 to your computer and use it in GitHub Desktop.
Is using this type of logic defeating the purpose of using interfaces/repositories? I like the idea because it means every time I define a new function on the model, I don't have to go into the Repository AND interface to define them too... yet it still allows me to swap out the Eloquent Repo's for something else if needed.
<?php namespace MyApp\Models\Repositories;
abstract class EloquentBaseRepository {
protected $methods;
protected $model;
public function __construct()
{
// Figure out the Model class name by exploding the namespace identifier (It contains the folder which = model name)
$model = explode('\\', get_class($this));
$this->model = new $model[count($model)-2];
}
public function __call($name, $args = array())
{
// Checks the method is in the array and is callable on the object.
if ( ! in_array($name, $this->methods) || ! is_callable(array($this->model, $name)))
{
throw new \Exception('The method '.$name.'() is not implemented');
}
// Takes the method call and sends it to the Model,
// in this example the model is "ModelName"
// and is stored in the normal laravel models directory (no namespacing)
return call_user_func_array(array($this->model, $name), $args);
}
}
// Model specific interfaces & repository would be stored in a directory like so: MyApp\Models\Repositories\ModelName
// Example Interface
<?php namespace MyApp\Models\Repositories\ModelName;
interface ModelNameRepositoryInterface {}
// Example Repository
<?php namespace MyApp\Models\Repositories\ModelName;
use MyApp\Models\Repositories\EloquentBaseRepository
;
class EloquentModelNameRepository extends EloquentBaseRepository implements ModelNameRepositoryInterface {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment