Last active
August 15, 2023 21:17
-
-
Save maximecolin/0d804cfb1dd4e9685b5e to your computer and use it in GitHub Desktop.
Symfony2 : Configuring the Request Context for CLI Command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
parameters: | |
router_context_host: acme.com | |
router_context_scheme: http |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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