-
Notifications
You must be signed in to change notification settings - Fork 718
Upgrading Silex 1.x to 2.x
- PHP 5.5+ or PHP 7.0+
Silex 2.x now uses a minimum of Symfony 2.8 and Pimple 3.0.
BC Break: Updated Pimple to 3.0
The upgrade to Pimple 3.0 has greatly simplified the way shared services are defined: services are now shared by default. If you rely on the old non-shared/factory behaviour, there's also a new way to define such services.
Silex 1.x shared service:
$app['service_name'] = $app->share(function () use ($app) { return new SampleService(); });
Silex 2.x shared service:
$app['service_name'] = function () use ($app) { return new SampleService(); };
Calling $app['service_name'] will create the sample service the first time; subsequent calls will return that same instance.
Silex 1.x factory service:
$app['factory_name'] = function () use ($app) { return SampleServiceFactory::get(); };
Silex 2.x factory service:
$app['factory_name'] = $app->factory(function () use ($app) { return SampleServiceFactory::get(); });
Calling $app['factory_name'] will return a new instance of SampleService every time (assuming that's what get() returns in this example).
BC Break: $app['request']
service removed, use $app['request_stack']
instead.
Whereas in Silex 1.x you could access the current request with $app['request']
or {{ app.request }}
, in Silex 2.x and above you have access to the full request stack. This is due to a change introduced in Symfony 2.4 that makes it easier to handle sub-requests.
To get backwards-compatible behaviour, you may have to call $app['request_stack']->getCurrentRequest()
or {{ app.request_stack.currentRequest }}
. Keep in mind that this new approach can return null
if you are not in a request context (e.g., running on the command line).