How To Use The Repository Pattern In Laravel
The Repository Pattern in Laravel is a very useful pattern with a couple of great uses. The first use is the abstraction that it provides. Meaning, it adds another layer between your application logic and your database.
Laravel Design Patterns( 2 Lessons )
There are various ways to structure the code and project for your web application. But it is usually a good idea to follow common design patterns because it will make your code easier to manage and easier for others to understand.
Many people must have heard the buzz about Repository Pattern in Laravel, in this post we will make it damn easy to understand why this is an important pattern and when to use it.
When tackling the separation of concerns, this is very important. Another benefit is how easy it makes it swap out your backend technology.
For instance, let’s say you are using MySQL and want to change to MongoDB. Since the Repository Pattern uses interfaces as contracts, your application logic will remain the same and all you have to do is change out the repository. Sounds easy, right?
Let’s dive in with a simple example.
Creating the Repository Interface
We need an interface to act as a contract for our repositories. What do I mean by contract?
Just like a written contract which describes the confines of a specific obligation, an interface is the same for our code.
It says that any class implementing the interface must perform specific actions. Or, in our case, must contain specific methods… Right.
I will use the blog scenario and create a post repository, as well as a comment repository. So, create a folder inside of the app
folder and name it Repositories
.
Then, create a file and name it PostRepositoryInterface.php
. This will be our interface. Within that interface, you will want to add this code:
- namespace App\Repositories;
- interface PostRepositoryInterface
- {
- }
Now, we will need the contracts, or methods, that we want our toPostRepository
implement. It will look something like this:
- namespace App\Repositories;
- interface PostRepositoryInterface
- {
- /**
- * Get's a post by it's ID
- *
- * @param int
- */
- public function get($post_id);
- /**
- * Get's all posts.
- *
- * @return mixed
- */
- public function all();
- /**
- * Deletes a post.
- *
- * @param int
- */
- public function delete($post_id);
- /**
- * Updates a post.
- *
- * @param int
- * @param array
- */
- public function update($post_id, array $post_data);
- }
Notice how there are no opening and closing curly braces. That is because no logic is stored in the interface – only the methods or declaration that we want our class to implement.
Creating the Repository
Now, we need to create our class. Within the same folder, Repositories
create a file and name it PostRepository.php
. For this class, we will use the implements
keyword to specify that we want to implement our interface. It should look like this:
- namespace App\Repositories;
- class PostRepository implements PostRepositoryInterface
- {
- }
We must create the methods that declared in our interface. If we don’t, we will get an error at runtime and we will not be able to use our class. Go ahead and add the logic that we will use to work without posts. For this, I will include our Eloquent model Post
.
- namespace App\Repositories;
- use App\Post;
- class PostRepository implements PostRepositoryInterface
- {
- /**
- * Get's a post by it's ID
- *
- * @param int
- * @return collection
- */
- public function get($post_id)
- {
- return Post::find($post_id);
- }
- /**
- * Get's all posts.
- *
- * @return mixed
- */
- public function all()
- {
- return Post::all();
- }
- /**
- * Deletes a post.
- *
- * @param int
- */
- public function delete($post_id)
- {
- Post::destroy($post_id)
- }
- /**
- * Updates a post.
- *
- * @param int
- * @param array
- */
- public function update($post_id, array $post_data)
- {
- Post::find($post_id)->update($post_data);
- }
- }
Our class is now happy because it is using all of the methods defined by our interface. Now that we have our class and our interface created, we need to register our repository with Laravel’s container.
Registering our Repository with Laravel’s IoC Container
Create a file called BackendServiceProvider.php
within the same folder – Repositories
. This file will serve as a connector to Laravel’s IoC Container and allow us to use dependency injection to inject our repository interfaces. More on that in a second …
Here is the BackendServiceProvider.php
:
- namespace App\Repositories;
- use Illuminate\Support\ServiceProvider;
- class BackendServiceProvider extends ServiceProvider
- {
- public function register()
- {
- $this->app->bind(
- 'App\Repositories\PostRepositoryInterface',
- 'App\Repositories\PostRepository'
- );
- }
- }
The one thing to notice here is the order in which the interface and the class are bound. If you try and bind App\Repositories\PostRepository
before App\Repositories\PostRepositoryInterface
, you will get an error. You must bind the interface first.
Still with me?
Just to make sure you’re following along, you should have a folder structure like this:
- - app
- --- Repositories
- ------ BackendServiceProvider.php
- ------ PostRepositoryInterface.php
- ------ PostRepository.php
Of course, there will be other folders and files within the app directory, I hope you get the point.
Using the Repository in a Controller
It’s time to use our shiny, new repository. The place to use this is our controller. I will assume that you have a PostController.php
class and that is your controller that handles everything to do with your posts. If you use some other controller, that is fine too.
What we want to do is inject our interface into the controller through its constructor when the controller gets instantiated. That way we can use the repository for all of our interactions with our posts model. Check it out:
- namespace App\Http\Controllers;
- use App\Http\Requests;
- use App\Repositories\PostRepositoryInterface;
- class PostController extends Controller
- {
- protected $post;
- /**
- * PostController constructor.
- *
- * @param PostRepositoryInterface $post
- */
- public function __construct(PostRepositoryInterface $post)
- {
- $this->post = $post;
- }
- /**
- * List all posts.
- *
- * @return mixed
- */
- public function index()
- {
- $data = [
- 'posts' => $this->post->all()
- ];
- return view('templates.posts', $data)
- }
- }
The first thing that we did is inject oursPostRepositoryInterface
into our constructor.
Then, we set our instance$post
variable to an instance of our objectPostRepository
through our interface. This allows us to call the methods in our classPostRepository
like we did in the methodindex()
. Now we can do something like this:
- $this->post->update($data_array);
- $this->post->delete($post_id);
- $this->post->get($post_id);
This keeps us from directly accessing our model like Post::find$id);
which adds another layer of abstraction to our application. Don’t forget, should we stop using MySQL and start using MongoDB, or some other backend technology, all we have to do is swap out our logicPostRepository
. This works because we are accessing the repository through our interface.
This means that the code in our controller would not change at all. That’s a big win!
More than one Repository? Sure
So, you need to create another repository because just having one repository is lame. Right? All you need to do is create an interface and then create a repository. Then, register them with Laravel’s IoC Container in our backend service provider file. I’ll use a Comment
model to show you how.
Our directory would now look like this:
In app folder
- - Repositories
- --- BackendServiceProvider.php
- ------ PostRepositoryInterface.php
- ------ PostRepository.php
- ------ CommentRepositoryInterface.php
- ------ CommentRepository.php
You would create the comment repository interface the same exact way as we did the post repository interface:
CommentRepositoryInterface.php
- namespace App\Repositories;
- interface CommentRepositoryInterface
- {
- // Define all methods here but remember not to use curly braces.
- public function all(); // Like this..
- }
And our CommentRepository.php
- namespace App\Repositories;
- use App\Comment;
- class CommentRepository implements CommentRepositoryInterface
- {
- // Must use all methods that were defined in the CommentRepositoryInterface here
- public function all()
- {
- return Comment::all();
- }
- }
The last thing that you will need to do is register it with the IoC Container in our BackendServiceProvider.php
. That file will now look like this…
- namespace App\Repositories;
- use Illuminate\Support\ServiceProvider;
- class BackendServiceProvider extends ServiceProvider
- {
- public function register()
- {
- $this->app->bind(
- 'App\Repositories\PostRepositoryInterface',
- 'App\Repositories\PostRepository'
- );
- $this->app->bind(
- 'App\Repositories\CommentRepositoryInterface',
- 'App\Repositories\CommentRepository'
- );
- }
- }
Again, pay attention to the order in which you list your interface and class.
Finished. Doesn’t that feel good? You should have a fully functional repository design pattern implemented with Laravel 5.
If you have any questions or comments about repository pattern in Laravel, please post them below.
How To Use The Repository Pattern In Laravel的更多相关文章
- Laravel与Repository Pattern(仓库模式)
为什么要学习Repository Pattern(仓库模式) Repository 模式主要思想是建立一个数据操作代理层,把controller里的数据操作剥离出来,这样做有几个好处: 把数据处理逻辑 ...
- Laravel Repository Pattern
Laravel Repository Pattern The Repository Pattern can be very helpful to you in order to keep your ...
- Follow me to learn what is repository pattern
Introduction Creating a generic repository pattern in an mvc application with entity framework is th ...
- Generic repository pattern and Unit of work with Entity framework
原文 Generic repository pattern and Unit of work with Entity framework Repository pattern is an abstra ...
- Using the Repository Pattern with ASP.NET MVC and Entity Framework
原文:http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-and ...
- Using Repository Pattern in Entity Framework
One of the most common pattern is followed in the world of Entity Framework is “Repository Pattern”. ...
- 学习笔记之ASP.NET MVC & MVVM & The Repository Pattern
ASP.NET MVC | The ASP.NET Site https://www.asp.net/mvc ASP.NET MVC gives you a powerful, patterns-ba ...
- [转]Using the Repository Pattern with ASP.NET MVC and Entity Framework
本文转自:http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-a ...
- Dapper and Repository Pattern in MVC
大家好,首先原谅我标题是英文的,因为我想不出好的中文标题. 这里我个人写了一个Dapper.net 的Repository模式的底层基础框架. 涉及内容: Dapper.net结合Repository ...
随机推荐
- 共阳极RGB LED二极管
1)RGB LED二极管有四个引脚,它把3个普通led被封装在其内部,这三个led颜色分别为红.绿.蓝三种颜色,通过控制各个LED的亮度,你可以混合出几乎任何你想要的颜色,如下图: 2)RGB LED ...
- mysql数据库语言分类
MySQL的sql语言分类DML.DQL.DDL.DCL. MySQL的sql语言分类DML.DQL.DDL.DCL. SQL语言一共分为4大类:数据定义语言DDL,数据操纵语言DML,数据查询语 ...
- Linux基础-04-权限
1. 查看文件的权限 1) 使用ls –l命令查看文件上所设定的权限. -rw-r--r-- 1 root root 605 Mar 18 20:28 .jp1.tar.gz 权限信息 属主 属组 文 ...
- 1.关于Python,你可能不知道的
启示录 写在前面———— 至于python有多牛逼,这里不介绍了,安装也不说了,网上一堆一堆的安装教程. 本文只介绍需要知道的 常识知识———— 1.python 发音:英 [ˈpaɪθən] 美 [ ...
- English Grammar in Use - Part1 Present and past
Unit 1 Present continuous (I am doing) A) Am/is/are + -ing is the Present continuous. B) I am doing ...
- youku项目总结(粗略总结)
一.ORM 之前我们都是以文件保存的形式存储数据,这次我们用的是数据库结合python使用,用到 ORM:关系型映射 类>>数据库的一张表 对象>>表一条记录 对象.属性> ...
- 如何将本地的项目添加到github上
参考链接:http://note.youdao.com/noteshare?id=d0b7990a83b024b0172b6d5c5617a8d0&sub=659F216B9046420991 ...
- RT-Flash imxrt 系列rt1052 rt1060量产神器宣传
转载: 恩智浦半导体2017年10月正式发布了业内首款跨界处理器—i.MX RT系列,超强的性能.超高的性价比使得i.MX RT系列火遍大江南北,一度成为基于MCU的产品主控首选,尤其是那些对于性能有 ...
- Linux下 sftp服务配置
查看openssh的版本,使用ssh -V 命令来查看openssh的版本,版本必须大于4.8p1,低于的这个版本需要升级. 参考博客:https://yq.aliyun.com/articles/6 ...
- @objc
Swift 和 Objective-C 的互调这个话题很大,今天我们重点看看其中一个小的知识点:@objc的使用. 用法 在 Swift 代码中,使用@objc修饰后的类型,可以直接供 Objecti ...