, (*1)
Slim-Symfony-Dependency-Injection-Bridge
Just a simple bridge to use the Symfony Dependency Injection Container to replace the Container in Slim Framework 3, (*2)
This will replace the pimple
container which comes default with Slim Framework 3., (*3)
The default services (like router
, request
, response
) which Slim Framework uses, are preloaded in the ContainerBuilder
. This way Slim will work as it should., (*4)
Installation
Use composer to install, (*5)
composer require flexsounds/slim-symfony-di-container
, (*6)
Default usage
To use the Symfony DI Container just add the ContainerBuilder to Slim\App
, (*7)
$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();
Default parameters
The default Slim Framework Settings are 1 on 1 mapped with parameters. To overwrite the settings you can either create a new ParameterBag
with your settings and pass it as the first argument to the ContainerBuilder
.
Or if you use one of the file loaders, change them with the parameters config key., (*8)
Just change the parameters to your own choice to your config file like this., (*9)
parameters:
httpVersion: "1.1"
responseChunkSize: 4096
outputBuffering: "append"
determineRouteBeforeAppMiddleware: false
displayErrorDetails: false
, (*10)
Other Examples
Example loading your dependencies through yaml configuration (The Symfony way)
$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();
````
Now you can create a `config.yml` file to load your services, parameters, etc. [The use of importing other config files is also available.](http://symfony.com/doc/current/cookbook/configuration/configuration_organization.html#different-directories-per-environment)
```yml
services:
my.custom.service:
class: Location\To\The\Class
Now the service my.custom.service
is available in the container. Use $this->get('my.custom.service')
to load the service., (*11)
$app->get('/', function($request, $response){
$customService = $this->get('my.custom.service'); // $customService is now an instance of Location\To\The\Class()
});
Read more
Read the symfony service container documentation to find out what other options are available in the service container., (*12)
Read the symfony dependency injection documentation to find out how the ContainerBuilder is used. Like setting default parameters., (*13)
Interesting to know
If you use PhpStorm as IDE and add the Symfony Plugin, typehinting for services should be available., (*14)