How to use the Symfony 2 Container in a legacy app

久未见 提交于 2019-12-03 07:02:30

Using Symfony's DIC as a standalone component is possible but you'd have to do many things "manually" (as you're not planning on using full Symfony Framework from the very beginning). You'll probably won't get much of using DIC with all that legacy stuff.

If you want to go this path I'd consider choosing another component first (like HttpFoundation and HttpKernel).

As @Cerad suggested you might wrap your legacy code in Symfony. Have a look at IngewikkeldWrapperBundle bundle. You can't use it as is but it might give you some ideas.

There's a third way.

You can decide to implement every new feature in a Symfony app. Than, you can make that both legacy and Symfony apps coexist. On a server level (i.e. Nginx), you might proxy legacy URLs to the legacy app and all the migrated URLs to a Symfony2 app. In my case this scenario was the best option and proved to be working. However, we were committed to abandon legacy app development (so every new feature or change had to be developed in a Symfony2 app).

Edit: here's how you could boot the Symfony kernel in a legacy app and dispatch an event (which is needed for the firewall):

$kernel = new \AppKernel('dev', true);
$kernel->boot();

$request = Request::createFromGlobals();
$request->attributes->set('is_legacy', true);
$request->server->set('SCRIPT_FILENAME', 'app.php');

$container = $kernel->getContainer();
$container->enterScope('request');
$container->get('request_stack')->push($request);
$container->set('request', $request);

$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$eventDispatcher = $container->get('event_dispatcher');
$eventDispatcher->dispatch('kernel.request', $event);

I believe you can access the container instance from your legacy application like this

$kernel = new AppKernel('prod', true);
$kernel->loadClassCache();
$kernel->boot();
$request = Request::createFromGlobals();
$container = $kernel->getContainer();
$sc = $container->get('security.context');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!