PHP解耦的三重境界(浅谈服务容器)

「七天自制PHP框架」已经开始连载,谢谢关注和支持!点击这里php

阅读本文以前你须要掌握:PHP语法,面向对象html

在完成整个软件项目开发的过程当中,有时须要多人合做,有时也能够本身独立完成,无论是哪种,随着代码量上升,写着写着就“失控”了,渐渐“丑陋接口,肮脏实现”,项目维护成本和难度上升,到了难以维持的程度,只有重构或者从新开发。程序员

第一重境界数据库

假设场景:咱们须要写一个处理类,可以同时操做会话,数据库和文件系统。咱们或许会这么写。数组

境界特征:能够运行,可是严重耦合session

class DB{
	public function DB($arg1,$arg2){
		echo 'constructed!'.PHP_EOL;
	}
}

class FileSystem{
	public function FileSystem($arg1,$arg2){
		echo 'constructed!'.PHP_EOL;
	}
}

class Session{
	public function Session($arg1,$arg2){
		echo 'constructed!'.PHP_EOL;
	}
}

class Writer{
	public function Write(){
		$db=new DB(1,2);
		$filesystem=new FileSystem(3,4);
		$session=new Session(5,6);
	}
}

$writer=new Writer();
$writer->write();

写法缺点:框架

1.在公有函数中构造对象,一旦涉及到如数据库参数的变更,修改会有很大的工做量函数

2.负责设计Writer类的人员须要对DB等类的各类API要熟悉this

有没有办法下降耦合度?设计

 

第二重境界(参数依赖)

假设场景:数据库地址由于客户不一样,须要常常更换,调用到DB的类不少(假若有几十个),但愿即便更改了数据库地址,也不用去修改这些类的代码。

class DB{
	public function DB($arg1,$arg2){
		echo 'constructed!'.PHP_EOL;
	}
}

class FileSystem{
	public function FileSystem($arg1,$arg2){
		echo 'constructed!'.PHP_EOL;
	}
}

class Session{
	public function Session($arg1,$arg2){
		echo 'constructed!'.PHP_EOL;
	}
}

class Writer{
	protected $_db;
	protected $_filesystem;
	protected $_session;
	public function Set($db,$filesystem,$session){
		$this->_db=$db;
		$this->_filesystem=$filesystem;
		$this->_session=$session;
	}
	public function Write(){
		
	}
}

$db=new DB(1,2);
$filesystem=new FileSystem(3,4);
$session=new Session(5,6);

$writer=new Writer();
$writer->Set($db,$filesystem,$session);
$writer->write();

虽然把DB类的构造移到了客户端,一旦涉及修改,工做量大大下降,可是新问题来了:为了建立一个Writer类,咱们须要先建立好DB类,FileSystem类等,这对负责涉及Writer类的人来讲,要求是很高的,他须要看不少其余类文档,一个个建立(可能还须要初始化),而后才能建立出他要的writer变量。

因此,咱们但愿,能有一种更好的写法,使得写Writer类的人,用一种更加快捷的接口,就能建立和调用他要的类,甚至连参数都不用填。

 

第三重境界(IOC容器)

通过前两重境界,咱们但愿能新增如下这些好处:

1.但愿DB类,Session类,FileSystem类“拿来即用”,不用每次繁琐的初始化,好比写$db=new DB(arg1,arg2);这类语句。

2.但愿DB等类型的对象是“全局”,在整个程序运行期间,随时能够调用。

3.调用DB等类型的程序员不用知道这个类太多的细节,甚至能够用一个字符串的别名来建立这样一个对象。

可以实现以上目标的就是IOC容器,能够把IOC容器简单的当作一个全局变量,并用关联数组把字符串和构造函数作绑定。

咱们先实现一个容器类

class Container{
	public $bindings;
	public function bind($abstract,$concrete){
		$this->bindings[$abstract]=$concrete;
	}
	public function make($abstract,$parameters=[]){
		return call_user_func_array($this->bindings[$abstract],$parameters);
	}
}

服务注册(绑定)

$container=new Container();
$container->bind('db',function($arg1,$arg2){
	return new DB($arg1,$arg2);
});

$container->bind('session',function($arg1,$arg2){
	return new Session($arg1,$arg2);
});

$container->bind('fs',function($arg1,$arg2){
	return new FileSystem($arg1,$arg2);
});

容器依赖

class Writer{
	protected $_db;
	protected $_filesystem;
	protected $_session;
	protected $container;
	public function Writer(Container $container){
		$this->_db=$container->make('db',[1,2]);
		$this->_filesystem=$container->make('session',[3,4]);
		$this->_session=$container->make('fs',[5,6]);
	}
}

$writer=new Writer($container);
相关文章
相关标签/搜索