Skip to content

Instantly share code, notes, and snippets.

@tbleckert
Created January 26, 2017 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbleckert/3800f4666439027d37f65c13bd35a13b to your computer and use it in GitHub Desktop.
Save tbleckert/3800f4666439027d37f65c13bd35a13b to your computer and use it in GitHub Desktop.
Repository pattern with Eloquent
<?php
namespace App\Repositories\Post;
use App\Post;
class EloquentPostRepository implements PostRepositoryInterface
{
protected $model;
public function __construct(Post $post)
{
$this->model = $post;
}
public function getPaginatedIndex()
{
return $this->model->orderBy('updated_at', 'desc')->paginate(20);
}
}
<?php
namespace App\Http\Controllers\Blog;
use App\Repositories\Post\PostRepositoryInterface;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PostController extends Controller
{
private $postRepository;
public function __construct(PostRepositoryInterface $postRepository)
{
$this->postRepository = $postRepository;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = $this->postRepository->getPaginatedIndex();
return view('blog.index', ['posts' => $posts]);
}
}
<?php
namespace App\Repositories\Post;
interface PostRepositoryInterface
{
/**
* Get a sorted, paginated list of
* blog posts to use on the blog index
*
* @return \Illuminate\Support\Collection
*/
public function getPaginatedIndex();
}
<?php
namespace App\Providers;
use App\Repositories\Post\EloquentPostRepository;
use App\Repositories\Post\PostRepositoryInterface;
use Illuminate\Support\ServiceProvider;
class PostServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind(PostRepositoryInterface::class, EloquentPostRepository::class);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [PostRepositoryInterface::class];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment