Laravel5中contracts详解_PHP
我们先来看看官方文档中对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接口还能看作一个简洁的文档便于阅读。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.
