Skip to content

Instantly share code, notes, and snippets.

@jmikola
Created March 6, 2012 07:47
Show Gist options
  • Save jmikola/1984761 to your computer and use it in GitHub Desktop.
Save jmikola/1984761 to your computer and use it in GitHub Desktop.
A cure for "localhost" appearing in absolute URL's when rendering a template from the Symfony2 CLI
<?php
namespace Application\ExerciseBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Overrides the default host for the Router's RequestContext service.
*
* This is necessary for generating URL's from a console command context, as the
* RouterListener never executes and initializes the RequestContext from a
* Request.
*/
class RouterRequestContextPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (false === $container->hasDefinition('router.request_context') || false === $container->hasParameter('exercise.host')) {
return;
}
$container
->getDefinition('router.request_context')
->replaceArgument(2, $container->getParameter('exercise.host'));
}
}
@beberlei
Copy link

beberlei commented Mar 6, 2012

+1! my solutions for this problem are uglier.

Same problem exists for sites behind proxies.

@schmittjoh
Copy link

You can add that to your console script, no?

@jmikola
Copy link
Author

jmikola commented Mar 7, 2012

I could certainly do this on a case-by-case basis from a ContainerAwareCommand. The main difference would be I'd have to modify the constructed RequestContext, rather than alter its definition. Consider adding this to the command's initialize() method:

$this->container->get('router')->getContext()->setHost('example.com');

The compiler pass seems more DRY, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment