Table of Contents
Laravel5中contracts详解
Home php教程 php手册 Laravel5中contracts详解

Laravel5中contracts详解

Jun 13, 2016 am 09:13 AM
Appear exist Detailed explanation

Laravel5中contracts详解

 在Laravel5中出现了一个新的东西,叫做contracts,那么它到底是什么?有什么用?怎么用?我们就来探讨下吧。

 

 

我们先来看看官方文档中对contracts的定义:

Laravel's Contracts are a set of interfaces that define the core services provided by the framework.
意思是说Laravel的Contracts是一个由 框架提供 的定义了 核心服务接口 的集合。

也就是说,每一个Contract都是一个接口,对应一个框架核心服务。

那它的意义何在?官网给出的解释也很简单:使用接口是为了 松耦合 和 简单 。

先不讲大道理,先来点干货,看看怎么使用contract

先浏览下contracts接口列表:

 

代码如下:


Illuminate\Contracts\Auth\Guard
Illuminate\Contracts\Auth\PasswordBroker
Illuminate\Contracts\Bus\Dispatcher
Illuminate\Contracts\Cache\Repository
Illuminate\Contracts\Cache\Factory
Illuminate\Contracts\Config\Repository
Illuminate\Contracts\Container\Container
Illuminate\Contracts\Cookie\Factory
Illuminate\Contracts\Cookie\QueueingFactory
Illuminate\Contracts\Encryption\Encrypter
Illuminate\Contracts\Routing\Registrar

 

…… 太多了,懒得继续贴了,官网手册里有。我们就拿 Illuminate\Contracts\Routing\Registrar 这个contract来演示一下吧。
首先,打开 app/Providers/AppServiceProvider.php,注意register方法:

 

代码如下:


public function register()
{
$this->app->bind(
'Illuminate\Contracts\Auth\Registrar',
'App\Services\Registrar'
);
}

 

$this->app 就是Application对象,也是容器对象,通过 $this->app->bind 方法我们绑定了一个实现Illuminate\Contracts\Auth\Registrar接口的类App\Services\Registrar。

注意,Illuminate\Contracts\Auth\Registrar就是一个contract。App\Services\Registrar 这个类文件在 app/Services/Registrar.php。

接着我们看 App\Http\Controllers\Auth\AuthController 这个控制器类,看到它有 __construct 构造函数:

 

代码如下:


public function __construct(Guard $auth, Registrar $registrar)
{
$this->auth = $auth;
$this->registrar = $registrar;

 

$this->middleware('guest', ['except' => 'getLogout']);
}

 

它有两个参数,对应的类命名空间在脚本开头可以看到:

 

代码如下:


use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;

 

这两个都是contract,但我们这里就拿 Registrar 说,我们注意到这里面只是通过参数类型指明了$registrar的接口类型,而实际调用的时候实际上是 App\Services\Registrar 这个类,这就是依赖注入的特性了,Laravel会自动在容器中搜索实现了接口Illuminate\Contracts\Auth\Registrar的类或对象,有的话就取出来作为实际参数传到构造函数里。

整个使用流程其实就可以总结为两个步骤:

向容器中注册实现contract接口的对象。
构造函数参数类型指定为contract接口类,框架会自动找到符合条件的对象。
那么再来说说contract的好处。

松耦合

官网给了一个例子解释什么是紧耦合以及Contract接口为何能够松耦合。

先来看看紧耦合的代码:

 

代码如下:


class Repository {
/**
* The cache.
*/
protected $cache;
/**
* Create a new repository instance.
*
* @param \SomePackage\Cache\Memcached $cache
* @return void
*/
public function __construct(\SomePackage\Cache\Memcached $cache)
{
$this->cache = $cache;
}
/**
* Retrieve an Order by ID.
*
* @param int $id
* @return Order
*/
public function find($id)
{
if ($this->cache->has($id))
{
//
}
}
}

 

可以看到构造函数中注入了一个详细的缓存实现 \SomePackage\Cache\Memcached ,如果换Redis作为缓存服务器或者更改了api方法,就需要修改,而如果项目很大,你不知道还有多少地方需要修改。

那么,Contract接口是如何解决这个问题的?请看代码:

 

代码如下:


use Illuminate\Contracts\Cache\Repository as Cache;
class Repository {
/**
* Create a new repository instance.
*
* @param Cache $cache
* @return void
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
}

 

注意,缓存实现我们使用了一个接口,也就是contract,Illuminate\Contracts\Cache\Repository,因为它只是接口,不需要关心背后是memcache还是redis。

简单性

如果所有服务都使用接口定义,就可以很简单的决定一个服务需要的功能,更加容易维护和扩展,并且contract接口还能看作一个简洁的文档便于阅读。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The first choice for CS players: recommended computer configuration The first choice for CS players: recommended computer configuration Jan 02, 2024 pm 04:26 PM

1. Processor When choosing a computer configuration, the processor is one of the most important components. For playing games like CS, the performance of the processor directly affects the smoothness and response speed of the game. It is recommended to choose Intel Core i5 or i7 series processors because they have powerful multi-core processing capabilities and high frequencies, and can easily cope with the high requirements of CS. 2. Graphics card Graphics card is one of the important factors in game performance. For shooting games such as CS, the performance of the graphics card directly affects the clarity and smoothness of the game screen. It is recommended to choose NVIDIA GeForce GTX series or AMD Radeon RX series graphics cards. They have excellent graphics processing capabilities and high frame rate output, and can provide a better gaming experience. 3. Memory power

Detailed explanation of the mode function in C++ Detailed explanation of the mode function in C++ Nov 18, 2023 pm 03:08 PM

Detailed explanation of the mode function in C++ In statistics, the mode refers to the value that appears most frequently in a set of data. In C++ language, we can find the mode in any set of data by writing a mode function. The mode function can be implemented in many different ways, two of the commonly used methods will be introduced in detail below. The first method is to use a hash table to count the number of occurrences of each number. First, we need to define a hash table with each number as the key and the number of occurrences as the value. Then, for a given data set, we run

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of remainder function in C++ Detailed explanation of remainder function in C++ Nov 18, 2023 pm 02:41 PM

Detailed explanation of the remainder function in C++ In C++, the remainder operator (%) is used to calculate the remainder of the division of two numbers. It is a binary operator whose operands can be any integer type (including char, short, int, long, etc.) or a floating-point number type (such as float, double). The remainder operator returns a result with the same sign as the dividend. For example, for the remainder operation of integers, we can use the following code to implement: inta=10;intb=3;

Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates Jul 26, 2023 am 08:57 AM

Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates. In Vue development, we often encounter situations where data needs to be updated asynchronously. For example, data needs to be updated immediately after modifying the DOM or related operations need to be performed immediately after the data is updated. The .nextTick function provided by Vue emerged to solve this type of problem. This article will introduce the usage of the Vue.nextTick function in detail, and combine it with code examples to illustrate its application in asynchronous updates. 1. Vue.nex

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

See all articles