I'm new to Symfony and am using 5.x. I have created a Console command using SymfonyComponentConsoleCommandCommand and am trying to use SymfonyComponentHttpClientHttpClient to POST to a URL. I need to generate the URL to a route running on the same machine (but in future this may possibly change to a different machine), so the host could be like localhost or example.com, and the port of the API is custom. I have searched on the web but the only possible solution I got involved the use of SymfonyComponentRoutingGeneratorUrlGeneratorInterface, and the web is cluttered with code samples for old versions of Symfony, and I haven't yet managed to get this working.
My latest attempt was:
public function __construct(UrlGeneratorInterface $router)
{
parent::__construct();
$this->router = $router;
}
but I don't really understand how to inject the parameter UrlGeneratorInterface $router to the constructor. I get an error that the parameter was not supplied. Do I have to create an instance of UrlGenerator elsewhere and inject it over here, or is there a simpler way to just generate an absolute URL in Symfony from within a Command? I don't really understand containers yet.
$url = $context->generate('view', ['Param' => $message['Param']], UrlGeneratorInterface::ABSOLUTE_URL);
services.yaml:
AppCommandMyCommand:
arguments: ['@router.default']
- Is there a simpler way to generate a URL from a Console Command by
explicitly specifying host, protocol, port, route, parameters etc?
- Why isn't UrlGeneratorInterface or RouterInterface autowiring?
- Do I need to specify wiring manually as $router.default in
services.yaml if I also have autowiring enabled?
- I understand that the execute function implementation may be
incorrect, but I couldn't get to fixing that without first getting
the constructor working. This is still, work in progress.
EDIT:
Updated gist: https://gist.github.com/tSixTM/86a29ee75dbd117c8f8571d458ed72db
EDIT 2: Made the problem statement clearer by adding question points: I slept on it :)
EDIT 3:
#!/usr/bin/env php
<?php
// application.php
require __DIR__.'/vendor/autoload.php';
use SymfonyComponentConsoleApplication;
$application = new Application();
$application->add(new AppCommandMyCommand());
$application->run();
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…