💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 依赖容器 ***** Slim使用一个可选的依赖项容器来准备、管理和注入应用程序依赖项。Slim支持像PHP-DI一样实现PSR-11的容器。 Slim uses an optional dependency container to prepare, manage, and inject application dependencies. Slim supports containers that implement[PSR-11](http://www.php-fig.org/psr/psr-11/)like[PHP-DI](http://php-di.org/doc/frameworks/slim.html). ## PHP-DI的示例用法 You don’t*have*to provide a dependency container. If you do, however, you must provide an instance of the container to`AppFactory`before creating an`App`. 您不必提供依赖容器。但是,如果这样做,则必须在创建 **$app** 之前向`AppFactory`提供容器的实例。 ~~~php <?php use DI\Container; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; require __DIR__ . '/../vendor/autoload.php'; // Create Container using PHP-DI $container = new Container(); // Set container to create App with on AppFactory AppFactory::setContainer($container); $app = AppFactory::create(); ~~~ 添加一个服务到您的容器: Add a service to your container: ~~~php $container->set('myService', function () { $settings = [...]; return new MyService($settings); }); ~~~ You can fetch services from your container explicitly as well as from inside a Slim application route like this: 你可以显式地从你的容器中获取服务,也可以从类似这样的slim应用程序路由中获取服务: ~~~php /** * Example GET route * * @param ServerRequestInterface $request PSR-7 request * @param ResponseInterface $response PSR-7 response * @param array $args Route parameters * * @return ResponseInterface */ $app->get('/foo', function (Request $request, Response $response, $args) { $myService = $this->get('myService'); // ...do something with $myService... return $response; }); ~~~ To test if a service exists in the container before using it, use the`has()`method, like this: 要在使用服务之前测试它是否存在于容器中,可以使用`has()`方法,如下所示: ~~~php /** * Example GET route * * @param ServerRequestInterface $request PSR-7 request * @param ResponseInterface $response PSR-7 response * @param array $args Route parameters * * @return ResponseInterface */ $app->get('/foo', function (Request $request, Response $response, $args) { if ($this->has('myService')) { $myService = $this->get('myService'); } return $response; }); ~~~