Pierstoval
2/18/2015 - 8:40 AM

Symfony2 : Configuring the Request Context for CLI Command

Symfony2 : Configuring the Request Context for CLI Command

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 }
parameters:
    router_context_host: acme.com
    router_context_scheme: http
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);
    }
}