PHP依赖倒置(Dependency Injection)代码实例
2015-01-24信息快讯网
这篇文章主要介绍了PHP依赖倒置(Dependency Injection)代码实例本文只提供实现代码,需要的朋友可以参考下
实现类:
<?php
class Container
{
protected $setings = array();
public function set($abstract, $concrete = null)
{
if ($concrete === null) {
$concrete = $abstract;
}
$this->setings[$abstract] = $concrete;
}
public function get($abstract, $parameters = array())
{
if (!isset($this->setings[$abstract])) {
return null;
}
return $this->build($this->setings[$abstract], $parameters);
}
public function build($concrete, $parameters)
{
if ($concrete instanceof Closure) {
return $concrete($this, $parameters);
}
$reflector = new ReflectionClass($concrete);
if (!$reflector->isInstantiable()) {
throw new Exception("Class {$concrete} is not instantiable");
}
$constructor = $reflector->getConstructor();
if (is_null($constructor)) {
return $reflector->newInstance();
}
$parameters = $constructor->getParameters();
$dependencies = $this->getDependencies($parameters);
return $reflector->newInstanceArgs($dependencies);
}
public function getDependencies($parameters)
{
$dependencies = array();
foreach ($parameters as $parameter) {
$dependency = $parameter->getClass();
if ($dependency === null) {
if ($parameter->isDefaultValueAvailable()) {
$dependencies[] = $parameter->getDefaultValue();
} else {
throw new Exception("Can not be resolve class dependency {$parameter->name}");
}
} else {
$dependencies[] = $this->get($dependency->name);
}
}
return $dependencies;
}
}
实现实例:
<?php
require 'container.php';
interface MyInterface{}
class Foo implements MyInterface{}
class Bar implements MyInterface{}
class Baz
{
public function __construct(MyInterface $foo)
{
$this->foo = $foo;
}
}
$container = new Container();
$container->set('Baz', 'Baz');
$container->set('MyInterface', 'Foo');
$baz = $container->get('Baz');
print_r($baz);
$container->set('MyInterface', 'Bar');
$baz = $container->get('Baz');
print_r($baz);
php中JSON的使用与转换
php5.4以下版本json不支持不转义内容中文的解决方法
PHP针对JSON操作实例分析
ucenter通信原理分析
Zend Guard使用指南及问题处理
php实现utf-8转unicode函数分享
windows中为php安装mongodb与memcache
php中fsockopen用法实例
ioncube_loader_win_5.2.dll的错误解决方法
PHP中使用xmlreader读取xml数据示例
dedecms集成财付通支付接口
为PHP5.4开启Zend OPCode缓存
PHP中require和include路径问题详解
CentOS6.5 编译安装lnmp环境
php中base64_decode与base64_encode加密解密函数实例
php中convert_uuencode()与convert_uuencode函数用法实例
php中call_user_func函数使用注意事项
Linux下安装oracle客户端并配置php5.3
php实现设计模式中的单例模式详解
php中字符集转换iconv函数使用总结
php json_encode()函数返回json数据实例代码
php返回json数据函数实例
自定义session存储机制避免会话保持问题
PHP中魔术变量__METHOD__与__FUNCTION__的区别
PHP5.3安装Zend Guard Loader图文教程
php中json_encode UTF-8中文乱码的更好解决方法
PHP错误Warning: Cannot modify header information - headers already sent by解决方法
PHP中file_get_contents高用法实例
php生成QRcode实例
当前比较流行的两款PHP加密、解密工具Zend Guard和iconCube介绍
ThinkPHP调用common/common.php函数提示错误function undefined的解决方法