vendredi 4 décembre 2015

One repository for multiple models

I have two similar Models: WebStore and LocalStore. A user is associated with one store through a polymorphic relation. I want to create a StoreRepository that takes the Class name (Model name which is saved as userable_type under user anyways) as an argument, and then saves that to $model property.

Ultimately I call the Stocker like:

$repo = new StoreRepository(Auth::user()->userable_type, Auth::user()->location->id);
$stocker = new \App\Entities\Stocker\Stocker($repo);

Location either returns "App\Models\WebStore" or "App\Models\LocalStore". I then save this later in the StoreRepo construct function to locationModel and under the model() function, the abstract function from the Repository, set the $this->model equal to it.

I have a Stocker service/entity:

class Stocker {

protected $repo;

public function __construct(StoreRepositoryInterface $repo) {
    $this->repo = $repo;
}

public function saleProducts() {
    return $this->repo->onSale()
}

}

I have a StoreRepository

class StoreRepository extends Repository implements StoreRepositoryInterface
{
    public $locationModel;
    public $id;

    public function __construct($locationModel, $id = null) {
        $this->locationModel = $locationModel;
        $this->id = $id;
    }

    public function model()
    {
        return $this->locationModel;
    }

    public function onSale($id) {
        $location = $this->model->findBy($id);
    }
}

Then I have a repository:

abstract class Repository implements RepositoryInterface {

    /**
     * @var App
     */
    private $app;

    /**
     * @var
     */
    protected $model;

    /**
     * @param App $app
     * @throws \Bosnadev\Repositories\Exceptions\RepositoryException
     */
    public function __construct(App $app) {
        $this->app = $app;
        $this->makeModel();
    }

    /**
     * Specify Model class name
     *
     * @return mixed
     */
    abstract function model();

    public function find($id, $columns = array('*')) {
        return $this->model->find($id, $columns);
    }
   public function makeModel() {

    $model = $this->app->make($this->model());

     return $this->model = $model->newQuery();
    }
}

Basically, every time I try to call one of Eloquent functions from Repositry, I get

Symfony\Component\Debug\Exception\FatalErrorException]
  Call to a member function find() on null

I believe this has to do with how I'm passing the model name in the StoreRep constructor. Any advice on how to use two models in one Repository would be appreciated.

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire