Skip to content

Instantly share code, notes, and snippets.

@maximecolin
Last active August 15, 2023 21:17
Show Gist options
  • Save maximecolin/0d804cfb1dd4e9685b5e to your computer and use it in GitHub Desktop.
Save maximecolin/0d804cfb1dd4e9685b5e to your computer and use it in GitHub Desktop.
Symfony2 : Configuring the Request Context for CLI Command
Did you ever try to send mail containing absolute url into command ?
Indeed, it doesn't work.
It's because there is no http request in CLI, so the context has no scheme and host.
Now you can do ```{{ url('homepage') }}``` to have absolute url in your mail templates.
<?php
namespace Acme\DemoBundle\EventListener;
use Symfony\Component\Routing\RouterInterface;
class ConsoleListener
{
/**
* @var RouterInterface
*/
private $router;
/**
* @var string
*/
private $host;
/**
* @var string
*/
private $scheme;
/**
* @var string
*/
private $baseUrl;
/**
* Constructor
*
* @param RouterInterface $router
* @param string $host
* @param string $scheme
* @param string $baseUrl
*/
public function __construct(RouterInterface $router, $host, $scheme = 'http', $baseUrl = null)
{
$this->router = $router;
$this->host = $host;
$this->scheme = $scheme;
$this->baseUrl = $baseUrl;
}
/**
* Mock router context on command
*/
public function onCommand()
{
$context = $this->router->getContext();
$context->setHost($this->host);
$context->setScheme($this->scheme);
$context->setBaseUrl($this->baseUrl);
}
}
parameters:
router_context_host: acme.com
router_context_scheme: http
services:
acme.demo.console.listener.command:
class: Acme\DemoBundle\EventListener\ConsoleListener
arguments:
- @router
- %router_context_host%
- %router_context_scheme%
tags:
- { name: kernel.event_listener, event: console.command, method: onCommand }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment