Created
May 2, 2014 18:33
-
-
Save paulofreitas/edfd30c101139d3ab1bf to your computer and use it in GitHub Desktop.
AbstractEloquentRepository
This file contains hidden or 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 | |
use Illuminate\Support\Collection; | |
abstract class AbstractEloquent implements BaseRepositoryInterface | |
{ | |
/** | |
* Model repository. | |
*/ | |
protected $resource; | |
/** | |
* The orderings for the query. | |
* | |
* @var array | |
*/ | |
protected $orders = []; | |
/** | |
* Relations to eager load. | |
* | |
* @var array | |
*/ | |
protected $with = []; | |
public function __construct($model) | |
{ | |
$this->resource = $model; | |
} | |
protected function newQuery() | |
{ | |
$query = $this->resource->newQuery(); | |
if ($this->orders) { | |
with(new Collection($this->orders))->each(function ($item) use ($query) { | |
$query->orderBy($item['column'], $item['direction']); | |
}); | |
} | |
return $query->with($this->with); | |
} | |
/** | |
* Being querying a repository with eager loading. | |
* | |
* @param array|string $relations | |
* @return self | |
*/ | |
public function with($relations) | |
{ | |
if (is_string($relations)) { | |
$relations = func_get_args(); | |
} | |
$this->with += $relations; | |
return $this; | |
} | |
/** | |
* Add an "order by" clause to the query. | |
* | |
* @param string $column | |
* @param string $direction | |
* @return self | |
*/ | |
public function orderBy($column, $direction = 'asc') | |
{ | |
$this->orders[] = compact('column', 'direction'); | |
return $this; | |
} | |
/** | |
* Retrieve all records from the database. | |
* | |
* @param $columns | |
* @return \Illuminate\Support\Collection | |
*/ | |
public function all(array $columns = ['*']) | |
{ | |
return new Collection($this->newQuery()->get($columns)->toArray()); | |
} | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment