DI依赖注入/IOC控制反转

 

DI依赖注入#

啥都不说,直接上代码php

<?php class UserController { private $user; function __construct(UserModel $user) { $this->user = $user; } } $user = new UserController(new UserMonel()); ?>

User控制器依赖UserModel,实例化的时候,直接注入。html

IOC控制反转#

先说IOC和DI的区别吧!laravel

  • IOC是一种设计思想
  • DI是一种设计模式

因此二者有本质上的区别。DI是IOC的一种实现方法(还有ServiceLocator等其余设计模式)。 所谓的反转,主要指由 主动依赖被动依赖设计模式

//主动依赖 function __construct() { $this->user = new UserModel(); } //被动依赖 function __construct(UserModel $user) { $this->user = $user; }

参考 浅谈IOC--说清楚IOC是什么架构

二.什么是IOC容器.#

IOC容器 是Laravel的核心设计模式,对于laravel的应用和理解是很是有必要深刻学习的!app

IOC思想实现了高度解耦,那么,问题来了,如何管理这些分散的模块呢?这就是容器的任务了!ide

能够想象成,在IOC容器中,装着(注册)不少模块。当用户须要一个模块的时候,能够从中拿出来。当提取的模块依赖另外一个模块的时候,容器会自动注入,再返回给用户(反射机制实现)。函数

是否是碉堡了?大批互相依赖的模块被完美解耦并统一管理了!学习

三.什么是服务提供者(ServiceProvider).#

假设模块一多,那么容器不是愈来愈大?每次加载,岂不是加载很久? 能不能弄一条管子,链接着模块,插在容器上,须要再经过管道获取呢?这样子,容器只是装着管头而已,就不怕被撑大了!this

这条管子就是 服务提供者

file

服务提供者自己也是一个类,不过这个类只有启动和注册两个函数。

/** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { //绑定到容器 $this->app->singleton( 'Riak\Contracts\Connection', function ($app) { return new Connection($app['config']['riak']); } ); }

服务提供者在config/app.php中配置,laravel自动注册到容器中。

'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class, ... /* * Application Service Providers... */ app\Providers\AppServiceProvider::class, app\Providers\AuthServiceProvider::class, ... ]

四.什么是门面(Facade).#

程序猿老是偷懒的,每次要模块,都要去容器里面拿,多麻烦啊!找我的代拿行不?这送货小哥就叫Facade门面。文档中叫静态代理。

送货小哥都是在config/app.php 中注册的。

'aliases' => [ 'App' => Illuminate\Support\Facades\App::class, 'Config' => Illuminate\Support\Facades\Config::class, 'Cookie' => Illuminate\Support\Facades\Cookie::class, 'Crypt' => Illuminate\Support\Facades\Crypt::class, 'DB' => Illuminate\Support\Facades\DB::class, 'Route' => Illuminate\Support\Facades\Route::class, ... ],

查看Illuminate\Support\Facades\Route代码,能够发现只有getAccessFacade()方法,这就是交代送啥货的函数,继承了Facade这个小哥基类。

class Route extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'router'; } }

注册了Facade门面后,就能够在任意地方使用了!

文档有详细的使用方式 Laravel 架构 — Facades

五.Application和Kernel#

不难发现,在引导程序开始初始化的时候,也就是在boostrap\app.php文件,里面一来就new了一个 Illuminate\Foundation\Application。下面分别注册了 Http\Kernel、Console\Kernel、Exceptions\Handler等。

这里能够这么理解,new一个Application,能够看做是创造了一个空间,这个空间初始化的时候,就会为本身注入一个容器,也就是在空间中放了一个容器。

Illuminate\Foundation\Application.php 中的 registerBaseBindings() 函数能够查看到容器注入源码。

至于kernel,能够当作是这个空间的工人,有各类各样的工人,每一个工人都有本身的工做。比如HttpKernel,负责处理http请求以及控制整个请求流程。

相关文章
相关标签/搜索