Dependency Container

Slim uses an optional dependency container to prepare, manage, and inject applicationdependencies. Slim supports containers that implement PSR-11 like PHP-DI.

Example usage with 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.

  1. <?php
  2. use DI\Container;
  3. use Psr\Http\Message\ResponseInterface as Response;
  4. use Psr\Http\Message\ServerRequestInterface as Request;
  5. use Slim\Factory\AppFactory;
  6. require __DIR__ . '/../vendor/autoload.php';
  7. // Create Container using PHP-DI
  8. $container = new Container();
  9. // Set container to create App with on AppFactory
  10. AppFactory::setContainer($container);
  11. $app = AppFactory::create();

Add a service to your container:

  1. $container->set('myService', function () {
  2. $settings = [...];
  3. return new MyService($settings);
  4. });

You can fetch services from your container explicitly as well as from inside a Slimapplication route like this:

  1. /**
  2. * Example GET route
  3. *
  4. * @param ServerRequestInterface $request PSR-7 request
  5. * @param ResponseInterface $response PSR-7 response
  6. * @param array $args Route parameters
  7. *
  8. * @return ResponseInterface
  9. */
  10. $app->get('/foo', function (Request $request, Response $response, $args) {
  11. $myService = $this->get('myService');
  12. // ...do something with $myService...
  13. return $response;
  14. });

To test if a service exists in the container before using it, use the has() method, like this:

  1. /**
  2. * Example GET route
  3. *
  4. * @param ServerRequestInterface $request PSR-7 request
  5. * @param ResponseInterface $response PSR-7 response
  6. * @param array $args Route parameters
  7. *
  8. * @return ResponseInterface
  9. */
  10. $app->get('/foo', function (Request $request, Response $response, $args) {
  11. if ($this->has('myService')) {
  12. $myService = $this->get('myService');
  13. }
  14. return $response;
  15. });