-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
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
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.