依赖注入的基本概念与背景
本内容深入探讨了PHP中依赖注入的核心概念,旨在为开发者提供实用的参考与思路。
以往阅读Laravel的IoC容器文档时,多侧重于实例演示而较少触及底层原理。在使用MVC框架期间,这一概念常被忽略。直到在Phalcon文档中看到详尽的原理阐述,才使思路豁然开朗。鉴于近期写作较少,现将这部分核心内容整理分享。
传统依赖管理的局限性分析
假设我们需要开发一个名为SomeComponent的组件,该组件在执行任务时需要依赖一个数据库连接。
若直接在SomeComponent内部实例化数据库连接,这种做法并不切实际。因为硬编码的方式导致我们无法灵活修改数据库连接参数或切换数据库类型。
class SomeComponent {
/**
* The instantiation of the connection is hardcoded inside
* the component so is difficult to replace it externally
* or change its behavior
*/
public function someDbTask()
{
$connection = new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
// ...
}
}
$some = new SomeComponent();
$some->someDbTask();
为解决上述问题,我们可以在组件外部预先创建连接,并通过某种方式注入到组件中。这看似是一个合理的解决方案:
class SomeComponent {
protected $_connection;
/**
* Sets the connection externally
*/
public function setConnection($connection)
{
$this->_connection = $connection;
}
public function someDbTask()
{
$connection = $this->_connection;
// ...
}
}
$some = new SomeComponent();
//Create the connection
$connection = new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
//Inject the connection in the component
$some->setConnection($connection);
$some->someDbTask();
然而,若在应用程序的不同位置多次使用该组件,将导致数据库连接被反复创建。此时,引入类似全局注册表的机制,从中获取唯一的数据库连接实例,而非每次新建,成为更优选择。
class Registry
{
/**
* Returns the connection
*/
public static function getConnection()
{
return new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
}
}
class SomeComponent
{
protected $_connection;
/**
* Sets the connection externally
*/
public function setConnection($connection){
$this->_connection = $connection;
}
public function someDbTask()
{
$connection = $this->_connection;
// ...
}
}
$some = new SomeComponent();
//Pass the connection defined in the registry
$some->setConnection(Registry::getConnection());
$some->someDbTask();
进一步设想,如果组件需要实现两个方法:一个是创建新的独立数据库连接,另一个是获取共享的连接实例:
class Registry
{
protected static $_connection;
/**
* Creates a connection
*/
protected static function _createConnection()
{
return new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
}
/**
* Creates a connection only once and returns it
*/
public static function getSharedConnection()
{
if (self::$_connection===null){
$connection = self::_createConnection();
self::$_connection = $connection;
}
return self::$_connection;
}
/**
* Always returns a new connection
*/
public static function getNewConnection()
{
return self::_createConnection();
}
}
class SomeComponent
{
protected $_connection;
/**
* Sets the connection externally
*/
public function setConnection($connection){
$this->_connection = $connection;
}
/**
* This method always needs the shared connection
*/
public function someDbTask()
{
$connection = $this->_connection;
// ...
}
/**
* This method always needs a new connection
*/
public function someOtherDbTask($connection)
{
}
}
$some = new SomeComponent();
//This injects the shared connection
$some->setConnection(Registry::getSharedConnection());
$some->someDbTask();
//Here, we always pass a new connection as parameter
$some->someOtherDbTask(Registry::getConnection());
至此,我们展示了如何利用依赖注入解决耦合问题。通过将依赖作为参数传递而非在代码内部创建,程序的维护性得以提升,代码耦合度降低,实现了松耦合架构。但从长远看,这种基础形式的依赖注入也存在缺陷。
例如,当组件包含大量依赖时,需编写多个Setter方法或通过构造函数传递所有参数。此外,每次使用组件都需手动创建其依赖项,增加了维护难度,代码可能变得冗长复杂:
//Create the dependencies or retrieve them from the registry
$connection = new Connection();
$session = new Session();
$fileSystem = new FileSystem();
$filter = new Filter();
$selector = new Selector();
//Pass them as constructor parameters
$some = new SomeComponent($connection, $session, $fileSystem, $filter, $selector);
// ... or using setters
$some->setConnection($connection);
$some->setSession($session);
$some->setFileSystem($fileSystem);
$some->setFilter($filter);
$some->setSelector($selector);
这意味着需要在应用多处重复创建对象。若不再需要某些依赖,还需回头移除构造函数参数或Setter方法。为解决此繁琐问题,我们再次借助全局注册表来创建组件,但在对象实例化前增加了一层抽象:
class SomeComponent
{
// ...
/**
* Define a factory method to create SomeComponent instances injecting its dependencies
*/
public static function factory()
{
$connection = new Connection();
$session = new Session();
$fileSystem = new FileSystem();
$filter = new Filter();
$selector = new Selector();
return new self($connection, $session, $fileSystem, $filter, $selector);
}
}
此时,我们似乎又回到了最初的问题起点——在组件内部处理依赖。不断修补寻找解决方案并非最佳实践。
使用容器优化依赖注入
一种实用且优雅的方案是使用容器进行依赖注入。如前所述,容器充当全局注册表,利用其作为桥梁管理依赖,能显著降低代码耦合度,简化组件复杂性:
class SomeComponent
{
protected $_di;
public function __construct($di)
{
$this->_di = $di;
}
public function someDbTask()
{
// Get the connection service
// Always returns a new connection
$connection = $this->_di->get('db');
}
public function someOtherDbTask()
{
// Get a shared connection service,
// this will return the same connection everytime
$connection = $this->_di->getShared('db');
//This method also requires a input filtering service
$filter = $this->_db->get('filter');
}
}
$di = new Phalcon\DI();
//Register a "db" service in the container
$di->set('db', function(){
return new Connection(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
));
});
//Register a "filter" service in the container
$di->set('filter', function(){
return new Filter();
});
//Register a "session" service in the container
$di->set('session', function(){
return new Session();
});
//Pass the service container as unique parameter
$some = new SomeComponent($di);
$some->someTask();
在该模式下,组件仅在访问特定服务时才初始化它,无需则不占用资源,从而实现高度解耦。组件的行为或其他方面互不影响。我们的具体实现方案如下:
Phalcon DI容器的核心功能
Phalcon\DI 是一个实现了服务依赖注入功能的组件,同时它本身也是一个容器。
由于Phalcon框架高度解耦,Phalcon\DI 成为集成其他组件不可或缺的部分。开发人员也可利用该组件对应用中不同类文件的实例进行依赖注入与管理。
本质上,该组件实现了控制反转(Inversion of Control)模式。基于此,对象不再通过构造函数接收参数或使用Setter方式注入,而是直接向依赖注入容器请求所需服务。这使得整体程序复杂度大幅降低,因为只需单一方法即可获取组件依赖。 此外,该模式增强了代码的可测试性,减少了出错概率。 接下来讨论如何在容器中注册服务。
服务注册与获取机制详解
无论是框架自身还是开发人员,均可注册服务。当组件A需要调用组件B(或其类的实例)时,可直接从容器中请求组件B,而非手动创建其实例。
这种工作机制带来了诸多优势:
我们可以轻松替换组件,无论是自行开发还是引入第三方库。 在组件发布前,我们能充分控制对象的初始化过程,并对对象进行各种预设设置。
我们可以通过统一的方式从组件获取结构化的全局实例。 服务可以通过以下几种方式注入到容器中:
//Create the Dependency Injector Container
$di = new Phalcon\DI();
//By its class name
$di->set("request", 'Phalcon\Http\Request');
//Using an anonymous function, the instance will lazy loaded
$di->set("request", function(){
return new Phalcon\Http\Request();
});
//Registering directly an instance
$di->set("request", new Phalcon\Http\Request());
//Using an array definition
$di->set("request", array(
"className" => 'Phalcon\Http\Request'
));
在上述示例中,当向框架请求访问请求数据时,系统首先会检查容器中是否存在名为“request”的服务。
容器将返回一个请求数据的实例,开发人员最终获得所需的组件。 前述每种方法各有优劣,具体选用哪种取决于开发过程中的特定场景。
使用字符串设定服务虽简单但缺乏灵活性;使用数组则提供更多灵活性,支持更复杂的代码逻辑。Lambda函数介于两者之间,提供了良好的平衡,但也可能带来更高的维护成本。
Phalcon\DI 支持服务的延迟加载。除非开发人员直接实例化对象并存入容器,否则通过数组、字符串等方式存储的服务将被延迟加载,即仅在请求对象时才进行初始化。
//Register a service "db" with a class name and its parameters
$di->set("db", array(
"className" => "Phalcon\Db\Adapter\Pdo\Mysql",
"parameters" => array(
"parameter" => array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "blog"
)
)
));
//Using an anonymous function
$di->set("db", function(){
return new Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "blog"
));
});
以上两种服务注册方式产生的结果相同。但通过数组定义的服务,在后续需要时可方便地修改服务参数:
$di->setParameter("db", 0, array(
"host" => "localhost",
"username" => "root",
"password" => "secret"
));
从容器获取服务最简单的方式是使用“get”方法,它将返回一个新的实例:
$request = $di->get("request");
或者通过以下魔术方法的形式调用:
$request = $di->getRequest();
Phalcon\DI 同时允许服务重用。若要获取已实例化过的服务,可使用 getShared() 方法: 具体的 Phalcon\Http\Request 请求示例:
$request = $di->getShared("request");
参数还可以在请求时,通过将数组参数传递给构造函数的方式注入:
$component = $di->get("MyComponent", array("some-parameter", "other"));
希望本文所述内容能对大家的PHP程序设计有所帮助。