burriko / cake-container
为 CakePHP 2.x 添加 League 的 DI 容器
Requires
- php: >=5.4.0
- composer/installers: *
- league/container: 1.*
This package is not auto-updated.
Last update: 2024-09-28 19:09:22 UTC
README
为 Cakephp 2 应用程序轻松添加良好的依赖注入容器。
这会安装 League 的容器,将其注入到控制器中,并将其添加到 CakeRegistry 中,这样您就可以在任何需要的地方以单例的形式访问它。
为什么?
我支持许多旧的 CakePHP 应用程序,没有容器或良好的 DI 方式让我感到烦恼。
安装
使用 composer 安装。
composer require burriko/cake-container
在 Config/bootstrap.php 中加载插件。Bootstrap 需要设置为 true。
CakePlugin::loadAll(['CakeContainer' => ['bootstrap' => true]]);
使用
在 Config/container.php 中创建一个文件来包含您的容器配置。在这里,您可以指定来自 League Container 文档 中的任何内容。例如,要加载服务提供者,您的配置文件将包含类似以下内容
<?php
$container->addServiceProvider(new Jobsoc\ServiceProvider\DocumentManagementServiceProvider);
查看 League Container 文档 以获取更多有用的示例。
修改 AppController 以实现 League\Container\ContainerAwareInterface 并使用 League\Container\ContainerAwareTrait 特性。
class AppController extends Controller implements League\Container\ContainerAwareInterface
{
use League\Container\ContainerAwareTrait;
}
在控制器中使用
您可以通过调用 $this->getContainer() 在控制器中访问容器。因此,要从您的服务提供者设置的名为 DocumentManagement 的类中获取实例,您可以在控制器中这样做。
$this->getContainer()->get(Jobsoc\DocumentSearch\DocumentManagement::class);
在壳中使用
您可以通过扩展 ContainerAwareShell 以与在控制器中相同的方式在壳中使用容器。最简单的方法是将 AppShell 更改为扩展 ContainerAwareShell。
<?php
App::uses('ContainerAwareShell', 'CakeContainer.Shell');
class AppShell extends ContainerAwareShell {}
在其他地方使用
如果您确实需要在控制器之外使用容器,您可以从 ClassRegistry 获取其实例。
ClassRegistry::getObject('container')->get('Jobsoc\DocumentSearch\DocumentManagement');