如何在Slim 4框架中将服务注入到Behat功能上下文中

时间:2019-12-03 15:29:02

标签: bdd slim behat slim-4

当我搜索针对特征上下文的服务注入时,总是会找到symfony的扩展名。但是在Slim 4框架中,我需要扩展或执行其他操作。

谢谢。

1 个答案:

答案 0 :(得分:0)

我用特质解决了这个问题。

    // 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);
        }
     }