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
.
<?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:
$container->set('myService', function () {
$settings = [...];
return new MyService($settings);
});
You can fetch services from your container explicitly as well as from inside a Slimapplication route like this:
/**
* 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:
/**
* 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;
});