Silex Providers in Symfony 4

Peter Lafferty
2 min readFeb 22, 2018

--

Moving across to Symfony from Silex my code had a lot of providers. If the provider just wired up classes and used type declarations then autowiring makes porting easy. However in some cases I needed to configure services slightly differently.

When the constructor has a param which is a scalar type or uses an interface then use the arguments param:

App\Service\DefaultService:
arguments:
$statistics: '@db.statistics'
$randomNumber: 10

When using interfaces wire a default class for all interfaces or use different concrete implementations in consuming classes:

App\ConnectionInterface:
class:
App\Connection

connection.statistics:
class:
App\Connection

App\ConnectionConsumer:
arguments:
$connection: '@connection.statistics'

For some third party classes it won’t be possible to pass parameters to configure the class but they might have methods for turning on and off features. These can be called with setter injection:

Monolog\Formatter\JsonFormatter:
calls:
- method: includeStacktraces

If the class is complicated to instantiate then the factory param can be used to create it:

App\Factory BuiltClass:
factory:
App\Factory::createFactoryBuiltClass

To pass the same parameter to multiple services bind parameters. This will inject the value for any param named $seed:

services:
# default configuration for services in *this* file
_defaults:
#...
bind:
$seed: 'ASDKFKEI£JDMASDASD'

Finally if you’re stuck and can’t figure out a way to get your old code to work with services.yaml you can put a PHP file under config/packages/ and Symfony will load this file allowing you to modify the container. Needless to say this is a bit of a hack:

<?php
// config/packages/hack.php
//do something hacky here and inject it in to the container
$container->setParameter('lol', 'so extra');

That’s a couple of ways to configure Silex providers as Symfony services.

--

--

Peter Lafferty

At least 8 months experience at something and a lifetime of loving JCVD movies.