当我搜索服务注入功能上下文时,我总是会找到 symfony 的扩展。但我需要扩展或其他东西才能在 Slim 4 框架中执行此操作。
谢谢你。
我使用一个特征解决了这个问题。
// src/Application/Utility/ContainerInjection.php
use DI\Container;
use DI\ContainerBuilder;
trait ContainerInjection
{
/**
* @return Container
*/
public function getContainer()
{
// To find project base path
// according to path where trait is found
$path_main = __DIR__ . '/../../../';
// Instantiate PHP-DI ContainerBuilder
$containerBuilder = new ContainerBuilder();
$settings = require $path_main . 'app/settings.php';
$dependencies = require $path_main . 'app/dependencies.php';
$settings($containerBuilder);
$dependencies($containerBuilder);
// Build PHP-DI Container instance
return $containerBuilder->build();
}
}
在 FeatureContext 中使用这个特性
class FeatureContext implements Context
{
use ContainerInjection;
private $myService;
public function __construct()
{
$container = $this->getContainer();
$this->myService = $container->get(MyService::class);
}
}