Skip to content

Instantly share code, notes, and snippets.

@rizqidjamaluddin
Last active December 21, 2015 13:12
Show Gist options
  • Save rizqidjamaluddin/fa5db4773fae76b56540 to your computer and use it in GitHub Desktop.
Save rizqidjamaluddin/fa5db4773fae76b56540 to your computer and use it in GitHub Desktop.
Generic Eloquent repository example
<?php
class ArticleRepository {
/**
* Because of how Eloquent works, an instance of a model is also a starting point to
* execute queries on it. This class should be instantiated by Laravel's IoC (e.g.
* constructor injection on a higher class, or App::make) so you never actually should
* need to do "new ArticleRepository(new Article)".
*
* @param Article $article
*/
public function __construct(Article $article) {
$this->model = $article;
}
/**
* Generic "get by ID" method.
*
* @param Int $id
* @throws ModelNotFoundException
* @return Article
*/
public function get($id) {
return $this->model->findOrFail($id);
}
/**
* A simple query.
*
* @return Collection
*/
public function getPublished() {
return $this->model->where('published', 1)->get();
}
/**
* Filtering "by relation". Using usual-style eloquent relationships in your models
* actually breaks the repository pattern, because they don't respect your
* repositories. Thus, if you had a Topic class and wanted to fetch articles from it,
* you would instantiate an ArticleRepository within it and use this method, passing
* itself as the argument.
*
* We're passing the _entire_ topic in here because other classes (including Topic)
* don't need to know what part of a topic this repository needs. It could use a slug
* instead of an ID, for instance.
*
* @param Topic $topic
* @return Collection
*/
public function getFromTopic(Topic $topic) {
return $this->model->where('topic_id', $topic->getId())->get();
}
/**
* Store an article in the repository. This is like Eloquent's save() method; may it be
* updating or creating, you use this - basically telling the repository, "keep this".
* This acts as a single choke point for data storage, allowing you to hook on extra
* behavior, like invalidaing old caches.
*
* Some people call is push() because they think of the repository as a collection. Some
* others call it put(). Or persist(). Call it whatever you want.
*
* @param Article $article
*/
public function push(Article $article) {
$article->save(); // feeling dirty now? You should.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment