首页 >

PHP依赖倒置(Dependency Injection)代码实例【PHP】

后端开发|php教程PHP依赖倒置(Dependency Injection)代码实例【PHP】
PHP,依赖倒置,Dependency,Inject
后端开发-php教程
实现类:
千图网 源码,vscode 标记行,ubuntu 光标,tomcat 自由舱,sqlite带表头查询,酒店预订时间插件,前端框架多页自动切换,黑色爬虫风水学,php 字符串 重复,石湾seo优化,网站模板素材怎么用,易语言网页操作模块,易企秀模板套用破解lzw

<?phpclass Container
{
protected $setings = array();

维基百科 网站 源码,用vscode做一个页面,ubuntu正常关机,tomcat处理请求的流程,爬虫控制web,php 移动开发框架,萧山区seo服务哪家好lzw
public function set($abstract, $concrete = null)
{
if ($concrete === null) {
$concrete = $abstract;
}
招聘管理系统 源码,vscode如何显示注释,ubuntu桌面性能,解压安装tomcat卸载,js如何使用sqlite3,小爬虫的启示说明了什么道理,php编写框架,seo兼职都有哪些排名,网站模板素材图片下载,aspcms的支付模板lzw
$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;
}
}

实现实例:

<?phprequire '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依赖倒置(Dependency Injection)代码实例【PHP】
  • PHP依赖倒置(Dependency Injection)代码实例【PHP】
  • PHP依赖倒置(Dependency Injection)代码实例【PHP】 | PHP依赖倒置(Dependency Injection)代码实例【PHP】 ...

    PHP依赖倒置(Dependency Injection)代码实例【PHP】
  • laravel中的Facades和Ioc Container还有ServiceProvider 思路分析?
  • laravel中的Facades和Ioc Container还有ServiceProvider 思路分析? | laravel中的Facades和Ioc Container还有ServiceProvider 思路分析? ...

    PHP依赖倒置(Dependency Injection)代码实例【PHP】
  • PHP依赖倒置(Dependency Injection)代码实例,依赖倒置原则
  • PHP依赖倒置(Dependency Injection)代码实例,依赖倒置原则 | PHP依赖倒置(Dependency Injection)代码实例,依赖倒置原则 ...