I am executing a task (command component) in Symfony2 and I would like to use
$this->getRequest()->getHost()
just like I do in a controller. What is the way to get that value (/Command/MyCommand.php)?
I know I can do $_SERVER['SERVER_NAME']
. But, I would like to use Symfony for this.
In case if you'd need host, you could get it from router context:
$host = $this->getContainer()->get('router')->getContext()->getHost();
But since you are looking for SERVER_NAME
- it will not be available during script executing from console.
Workaround for this situation could be to define your parameter in parameters and get it Command
:
$serverName = $this->getContainer()->getParameter('your_defined_param');
I know this is a really old question, but it's ranking high in the Google results.
Since Symfony 2.1 you can add additional fields to parameters.yml
# app/config/parameters.yml
parameters:
router.request_context.host: example.org
router.request_context.scheme: https
router.request_context.base_url: my/path
This is applicable to all versions up to Symfony 4.1
It's worth mentioning that you'll also have to use url (absolute) rather than path (relative)
Link to the manual Symfony.com - How to Generate URLs from the Console