Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cuber's avatar

Repositories & Inheritance

I have setup my ModelRepository Interface and its EloquentModelRepository class. I am binding the implementation using a DatabaseServiceProvider and a Cache Decorator like so

$this->app->singleton(ModelRepository::class, function()
{
            return new CachingModelRepository(
                new EloquentModelRepository(new App\Models\Model ),
                $this->app['cache.store']
            );
});

It works, however im wondering whether it is correct instantiate a "Model" like this since it is required by EloquentModelRepository's constructor..

thank you

0 likes
2 replies
michaeldyrynda's avatar

I have an abstract EloquentRepository that my Eloquent<Entity>Repository extends. In my EloquentRepository, I set the model I wish to instantiate:

abstract class EloquentRepository implements EloquentRepositoryInterface {

    protected $model;

    protected $modelName;

    /**
     * Initialise a new model
     */
    final public function __construct()
    {
        $this->model = new $this->modelName;
    }
}

class EloquentClientRepository extends EloquentRepository implements ClientRepositoryInterface {

    /**
     * @var string
     */
    protected $modelName = 'Jms\Modules\Clients\Models\Client';
}

Lastly, I bind my implementation to the IoC container

$this->app->bind('\Jms\Modules\Clients\Repositories\ClientRepositoryInterface', '\Jms\Modules\Clients\Repositories\EloquentClientRepository')

This way I can have generic methods that apply to all repositories in my EloquentRepository and entity-specific methods in my Eloquent<Entity>Repository classes.

Please or to participate in this conversation.