Skip to content

Instantly share code, notes, and snippets.

Created August 27, 2013 22:37
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save anonymous/4dafa3379b1f27167269 to your computer and use it in GitHub Desktop.
Save anonymous/4dafa3379b1f27167269 to your computer and use it in GitHub Desktop.
Quick and dirty illustration of my comment to MKStandard on reddit. I know this could be improved - especially as the BaseRepository is assuming it uses Eloquent models (maybe an AbstractRepository that gets extended by an EloquentBaseRepository would be another logical layer of abstraction?) - but I think this should be enough of an illustratio…
<?php
class BaseRepository {
/**
* our model instance
*
* @var $model
*/
protected $model = null;
/**
* get our model
*
* @return $model
*/
protected function getModel()
{
return $this->model;
}
/**
* set our model
*
* @return void
*/
protected function setModel($model)
{
$this->model = $model;
}
public function get($id, array $related = null)
{
if(is_array($id))
{
$results = $this->model->whereIn("id", $id)->get();
}
else
{
$results = $this->model->findOrFail($id);
}
if( ! is_null($related))
{
$results->load($related);
}
return $results;
}
}
class EloquentMeasurementRepository extends BaseRepository implements MeasurementRepositoryInterface
{
public function __construct(Measurement $model)
{
$this->setModel($model);
}
}
@abbajbryant
Copy link

You might also want to wrap the interior of the get function in an if (!is_null($this->model)){ ... } or similar to prevent trying to use null as a model. Like I said, quick and dirty.

@BastianHofmann
Copy link

Accessor or Mutators should be public or removed. In the constructor for EloquentMeasurementRepository you can set the model like this: $this->model = $model.

This also works but that's not what accessor and mutators are meant for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment