flexsounds/slim-symfony-di-container

用于在 Slim 框架 3 中使用 Symfony 依赖注入容器的桥梁

2.0.0-RC1 2019-03-17 16:02 UTC

This package is auto-updated.

Last update: 2024-08-27 18:19:39 UTC


README

Travis Build Status Packagist Packagist

Slim-Symfony-Dependency-Injection-Bridge

只是一个简单的桥梁,用于使用 Symfony 依赖注入容器来替换 Slim 框架 3 中的 Container

这将替换 Slim 框架 3 默认的 pimple 容器。

Slim 框架使用的默认服务(如 routerrequestresponse)已预先加载到 ContainerBuilder 中。这样 Slim 将正常工作。

安装

使用 composer 安装

composer require flexsounds/slim-symfony-di-container

默认用法

要使用 Symfony DI 容器,只需将 ContainerBuilder 添加到 Slim\App

$container = new \Flexsounds\Component\SymfonyContainerSlimBridge\ContainerBuilder();

$app = new \Slim\App($container);

// define your routes here. The container is available through $this in the route closure

$app->run();

默认参数

默认的 Slim 框架设置与参数一一对应。要覆盖设置,您可以创建一个新的 ParameterBag 并用您的设置传递给它,作为 ContainerBuilder 的第一个参数。或者,如果您使用的是文件加载器之一,可以更改它们中的参数配置键。

只需将参数更改为您自己的选择,如下所示更改配置文件。

parameters:
   httpVersion: "1.1"
   responseChunkSize: 4096
   outputBuffering: "append"
   determineRouteBeforeAppMiddleware: false
   displayErrorDetails: false

其他示例

示例:通过 yaml 配置(Symfony 方式)加载依赖项

$container = new \Flexsounds\Component\SymfonyContainerSlimBridge\ContainerBuilder();
$loader = new \Symfony\Component\DependencyInjection\Loader\YamlFileLoader($container, new \Symfony\Component\Config\FileLocator(__DIR__));
$loader->load('config.yml');

$app = new \Slim\App($container);

$app->run();

现在您可以创建一个 config.yml 文件来加载服务、参数等。 还可以使用其他配置文件导入。

services:
  my.custom.service:
    class: Location\To\The\Class

现在服务 my.custom.service 可在容器中使用。使用 $this->get('my.custom.service') 来加载服务。

$app->get('/', function($request, $response){
  $customService = $this->get('my.custom.service'); // $customService is now an instance of Location\To\The\Class()
});

阅读更多

阅读 symfony 服务容器文档 了解服务容器中可用的其他选项。

阅读 symfony 依赖注入文档 了解如何使用 ContainerBuilder,例如设置默认参数。

有趣的是知道

如果您使用 PhpStorm 作为 IDE 并添加 Symfony 插件,则应该可以使用服务类型提示。