PHP 语言 使用PSR 11标准实现依赖注入容器

PHP阿木 发布于 13 天前 3 次阅读


摘要:依赖注入(Dependency Injection,简称DI)是一种设计模式,旨在将对象的依赖关系从对象自身中分离出来,由外部进行注入。PSR-11是PHP框架标准组制定的一个关于依赖注入容器的规范。本文将围绕PHP语言,使用PSR-11标准实现一个简单的依赖注入容器,并探讨其原理和应用。

一、

随着软件架构的复杂化,依赖注入已成为现代软件开发中不可或缺的一部分。它有助于提高代码的可维护性、可测试性和可扩展性。PHP作为一门流行的编程语言,也有许多优秀的依赖注入容器实现。本文将基于PSR-11标准,实现一个简单的PHP依赖注入容器。

二、PSR-11标准简介

PSR-11是PHP框架标准组制定的一个关于依赖注入容器的规范。它定义了依赖注入容器的基本接口和功能,使得不同的依赖注入容器之间可以相互兼容。PSR-11标准主要包括以下几个部分:

1. ContainerInterface:定义了依赖注入容器的基本接口,包括方法:get()、has()、make()等。

2. ParameterBagInterface:定义了参数包接口,用于存储容器中的参数。

3. ExceptionInterface:定义了异常接口,用于处理容器中的错误。

三、实现依赖注入容器

下面是一个基于PSR-11标准的PHP依赖注入容器的简单实现:

php

<?php


namespace DIContainer;

use DIContainerExceptionNotFoundException;


use DIContainerExceptionNotInstantiableException;

interface ContainerInterface


{


public function get($id);


public function has($id);


public function make($id, array $parameters = []);


}

class Container implements ContainerInterface


{


private $bindings = [];


private $instances = [];

public function get($id)


{


if ($this->has($id)) {


return $this->resolve($id);


}


throw new NotFoundException("No binding found for: {$id}");


}

public function has($id)


{


return isset($this->bindings[$id]);


}

public function make($id, array $parameters = [])


{


if ($this->has($id)) {


$concrete = $this->bindings[$id];


if (is_callable($concrete)) {


return $this->call($concrete, $parameters);


}


return $concrete;


}


throw new NotFoundException("No binding found for: {$id}");


}

private function resolve($id)


{


$concrete = $this->bindings[$id];


if (is_callable($concrete)) {


return $this->call($concrete);


}


return $concrete;


}

private function call($concrete, array $parameters = [])


{


if (is_string($concrete)) {


$concrete = $this->bindings[$concrete];


}


if (!is_callable($concrete)) {


throw new NotInstantiableException("Cannot instantiate: {$concrete}");


}


return $concrete(...$parameters);


}


}


四、使用依赖注入容器

下面是一个使用上述依赖注入容器的示例:

php

<?php


namespace Example;

use DIContainerContainer;

class Logger


{


public function log($message)


{


echo $message . PHP_EOL;


}


}

class App


{


private $logger;

public function __construct(Logger $logger)


{


$this->logger = $logger;


}

public function run()


{


$this->logger->log('App is running...');


}


}

$container = new Container();


$container->bind(Logger::class, Logger::class);


$app = $container->make(App::class);


$app->run();


五、总结

本文介绍了PSR-11标准,并实现了一个简单的PHP依赖注入容器。通过依赖注入容器,我们可以将对象的依赖关系从对象自身中分离出来,由外部进行注入,从而提高代码的可维护性、可测试性和可扩展性。在实际项目中,我们可以根据需要扩展依赖注入容器的功能,使其更加完善。