我试图了解依赖注入,我理解它,大部分时间。
但是,如果由于某种原因,我的一个类依赖于几个类,而不是将所有这些都传递给构造函数中的这个类,是否有更好,更明智的方法?
我听说过DI容器,这就是我要解决这个问题的方法吗?我应该从哪里开始这个解决方案?我是否将依赖项传递给我的DIC,然后将其传递给需要这些依赖项的类?
任何有助于我指向正确方向的帮助都会非常棒。
答案 0 :(得分:30)
人们应该真的不要混淆他们。 Dependency Injection的想法来自Dependency Inversion principle。
DIC是“魔法治疗”,它承诺允许你使用依赖注入,但在PHP中通常是通过打破面向对象编程的所有其他原则来实现的。最差的实现往往通过静态Registry
或Singleton
将它全部附加到全局状态。
无论如何,如果你的课程依赖于太多其他课程,那么一般来说,它意味着课堂本身的设计缺陷。你基本上有一个有太多理由要改变的类,因此打破了Single Responsibility principle。
在这种情况下,依赖注入容器只会隐藏底层设计问题。
如果您想了解更多有关依赖注入的信息,我建议您在youtube上观看“清洁代码会谈”:
答案 1 :(得分:12)
如果您有多个依赖项需要处理,那么可以使用DI容器作为解决方案。
DI容器可以是由您需要的各种依赖对象构造的对象或数组,它将传递给构造函数并解压缩。
假设您需要一个配置对象,一个数据库连接和一个传递给每个类的客户端信息对象。您可以创建一个包含它们的数组:
// Assume each is created or accessed as a singleton, however needed...
// This may be created globally at the top of your script, and passed into each newly
// instantiated class
$di_container = array(
'config' = new Config(),
'db' = new DB($user, $pass, $db, $whatever),
'client' = new ClientInfo($clientid)
);
您的类构造函数接受DI容器作为参数:
class SomeClass {
private $config;
private $db;
private $client;
public function __construct(&$di_container) {
$this->config = $di_container['config'];
$this->db = $di_container['db'];
$this->client = $di_container['client'];
}
}
我可能还会将DI容器创建为类本身,并使用单独注入其中的组件类来实例化它,而不是像上面所做的那样(这很简单)。使用对象而不是数组的一个好处是,默认情况下,它将通过引用传递给使用它的类,而数组通过值传递(尽管数组中的对象仍然是引用)。
在某些方面,对象比数组更灵活,尽管最初编码起来比较复杂。
容器对象也可以在其构造函数中创建/实例化包含的类(而不是在外部创建它们并将它们传入)。这可以为每个使用它的脚本节省一些编码,因为您只需要实例化一个对象(它本身实例化其他几个)。
Class DIContainer {
public $config;
public $db;
public $client;
// The DI container can build its own member objects
public function __construct($params....) {
$this->config = new Config();
// These vars might be passed in the constructor, or could be constants, or something else
$this->db = new DB($user, $pass, $db, $whatever);
// Same here - the var may come from the constructor, $_SESSION, or somewhere else
$this->client = new ClientInfo($clientid);
}
}
答案 2 :(得分:0)
我已就此问题撰写article。 ideea是使用抽象工厂和依赖注入的组合来实现(可能的嵌套)依赖项的透明依赖性解析。我将在这里复制/粘贴主要代码片段:
namespace Gica\Interfaces\Dependency;
interface AbstractFactory
{
public function createObject($objectClass, $constructorArguments = []);
}
抽象工厂实现是:
namespace Gica\Dependency;
class AbstractFactory implements \Gica\Interfaces\Dependency\AbstractFactory, \Gica\Interfaces\Dependency\WithDependencyInjector
{
use WithDependencyInjector;
/**
* @param string $objectClass
* @param array $constructorArguments
* @return object instanceof $class
*/
public function createObject($objectClass, $constructorArguments = [])
{
$instance = new $objectClass(...$constructorArguments);
$this->getDependencyInjector()->resolveDependencies($instance);
return $instance;
}
}
依赖注入器是这样的: 命名空间Gica \ Dependency;
class DependencyInjector implements \Gica\Interfaces\Dependency\DependencyInjector
{
use \Gica\Traits\WithDependencyContainer;
public function resolveDependencies($instance)
{
$sm = $this->getDependencyInjectionContainer();
if ($instance instanceof \Gica\Interfaces\WithAuthenticator) {
$instance->setAuthenticator($sm->get(\Gica\Interfaces\Authentication\Authenticator::class));
}
if ($instance instanceof \Gica\Interfaces\WithPdo) {
$instance->setPdo($sm->get(\Gica\SqlQuery\Connection::class));
}
if ($instance instanceof \Gica\Interfaces\Dependency\WithAbstractFactory) {
$instance->setAbstractFactory($sm->get(\Gica\Interfaces\Dependency\AbstractFactory::class));
}
//... all the dependency declaring interfaces go below
}
}
dependency container是标准的。 客户端代码可能如下所示:
$abstractFactory = $container->get(\Gica\Interfaces\Dependency\AbstractFactory::class);
$someHelper = $abstractFactory->createObject(\Web\Helper\SomeHelper::class);
echo $someHelper->helpAction();
请注意,依赖项是隐藏的,我们可以专注于主要业务。我的客户代码并不关心或知道$ someHelper需要Authenticator
或者helpAction需要SomeObject
来完成其工作;
在后台发生了很多事情,检测,解决和注入了很多依赖项。
请注意,我没有使用new
运算符来创建$someObject
。实际创建对象的责任感传递给AbstractFactory
P.S。 Gica 是我的昵称:)
答案 3 :(得分:-6)
我建议你使用Singltones或Mutlitones。在这些情况下,您将始终能够通过静态类方法获取对象。
另一种方法(找不到正确的模式名称,但可能是Registry
)是使用一个全局静态对象来存储多个对象的实例。例如。 (简化代码,没有任何检查):
class Registry {
private static $instances = array();
public static function add($k, $v) {
$this->instances[$k] = $v;
}
public static function get($k) {
return $this->instances[$k];
}
}
class MyClass {
public function __construct() {
Registry::add('myclass', $this);
}
}