When working with Symfony console commands, you might need to generate URLs pointing to routes defined in the application. While this is straightforward for relative URLs, generating absolute URLs inside commands requires a bit of configuration. Unlike controllers, console commands are not executed within an HTTP request. Because of that, Symfony does not automatically know which host and scheme to use. By default, it falls back to http://localhost. This tutorial explains how to generate absolute URL in console command in Symfony 8 application.
First, define the base URL in the .env file that Symfony should use when there is no HTTP request context. You can add a new environment variable or update it if it already exists.
.env
DEFAULT_URI=http://example.com
Next, tell the Symfony router to use this value as its default request context. This ensures that URL generation from non-HTTP environments (like console commands) works correctly.
config/packages/routing.yaml
framework:
router:
default_uri: '%env(DEFAULT_URI)%'
For demonstration purposes, define a simple route that we will reference from a console command.
src/Controller/TestController.php
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class TestController
{
#[Route('/test', name: 'test')]
public function index(): Response
{
return new Response();
}
}
Now create a console command and inject the UrlGeneratorInterface. This service allows us to generate URLs in the same way as in controllers or other services.
src/Command/TestCommand.php
<?php
namespace App\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
#[AsCommand(name: 'app:test')]
class TestCommand extends Command
{
public function __construct(private UrlGeneratorInterface $urlGenerator)
{
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$url = $this->urlGenerator->generate(
'test',
referenceType: UrlGeneratorInterface::ABSOLUTE_URL,
);
$output->writeln($url); // http://example.com/test
return self::SUCCESS;
}
}
After running the command, Symfony will output an absolute URL using the host and scheme defined in the variable DEFAULT_URI, instead of defaulting to http://localhost.
Leave a Comment
Cancel reply