Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example implementation of a Eloquent-based repository that provides a fluent interface for sorting and pagination without exposing the underlying model API.
<?php
class EloquenFooRepository
{
/**
* The base eloquent model
* @var Eloquent
*/
protected $model;
/**
* The current sort field and direction
* @var array
*/
protected $currentSort = array('created_at', 'desc');
/**
* The current number of results to return per page
* @var integer
*/
protected $perPage = 25;
public function __construct(Foo $model)
{
$this->model = $model;
}
/**
* Sets the number of items displayed per page of results
* @param integer $perPage The number of items to display per page
* @return EloquenFooRepository The current instance
*/
public function paginate($perPage)
{
$this->perPage = (int) $perPage;
return $this;
}
/**
* Sets how the results are sorted
* @param string $field The field being sorted
* @param string $direction The direction to sort (ASC or DESC)
* @return EloquenFooRepository The current instance
*/
public function sortBy($field, $direction = 'DESC')
{
$direction = (strtoupper($direction) == 'ASC') ? 'ASC' : 'DESC';
$this->currentSort = array($field, $direction);
return $this;
}
/**
* Creates a new QueryBuilder instance and applies the current sorting
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function query()
{
list($sortField, $sortDir) = $this->currentSort;
return $this->model->newQuery()->orderBy($sortField, $sortDir);
}
/**
* Retrieves a set of items based on a single value
* @param string $fieldName The name of the field to match
* @param string $fieldValue The value of the field to match
* @return Illuminate\Pagination\Paginator|Illuminate\Support\Collection
*/
public function getByField($fieldName, $fieldValue)
{
$query = $this->query()->where($fieldName, $fieldValue);
return ($this->perPage > 0) ? $query->paginate($this->perPage) : $query->get();
}
}
<?php
class FooService
{
protected $repo;
public function __construct(EloquentFooRepository $repo)
{
$this->repo = $repo;
}
/**
* Retrieves all Foos by Bar, optionally sort and paginate results
* @param string $barValue The value of bar to match
* @param string $sortBy The field by which to sort results
* @param string $sortDir The direction to sort results
* @param string $perPage If specified, paginates results by the given number of items per page
*/
public function getFoosByBar($barValue, $sortBy = 'bar', $sortDir = 'desc', $perPage = 0)
{
if($perPage > 0) {
$this->repo->paginate($perPage);
}
return $this->repo->sortBy($sortBy, $sortDir)->getByField('bar', $barValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.