In Symfony 4 non sono riuscito a far funzionare $this->getContainer()->get('templating')->render($view, $parameters);
.
ho impostato l'uso dello spazio dei nomi per Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand
ed esteso ContainerAwareCommand class EmailCommand extends ContainerAwareCommand
ottengo un eccezione generata
[Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException]
You have requested a non-existent service "templating".
Per Symfony 4, questa è la soluzione mi è venuta.
Prima ho installato Twig.
composer require twig
poi creato il mio proprio servizio ramoscello.
<?php
# src/Service/Twig.php
namespace App\Service;
use Symfony\Component\HttpKernel\KernelInterface;
class Twig extends \Twig_Environment {
public function __construct(KernelInterface $kernel) {
$loader = new \Twig_Loader_Filesystem($kernel->getProjectDir());
parent::__construct($loader);
}
}
Ora il mio comando di posta elettronica è simile a questo.
<?php
# src/Command/EmailCommand.php
namespace App\Command;
use Symfony\Component\Console\Command\Command,
Symfony\Component\Console\Input\InputInterface,
Symfony\Component\Console\Output\OutputInterface,
App\Service\Twig;
class EmailCommand extends Command {
protected static $defaultName = 'mybot:email';
private $mailer,
$twig;
public function __construct(\Swift_Mailer $mailer, Twig $twig) {
$this->mailer = $mailer;
$this->twig = $twig;
parent::__construct();
}
protected function configure() {
$this->setDescription('Email bot.');
}
protected function execute(InputInterface $input, OutputInterface $output) {
$template = $this->twig->load('templates/email.html.twig');
$message = (new \Swift_Message('Hello Email'))
->setFrom('[email protected]')
->setTo('[email protected]')
->setBody(
$template->render(['name' => 'Fabien']),
'text/html'
);
$this->mailer->send($message);
}
}
fonte
2018-02-19 19:25:34
Grazie, è così che funziona perfettamente. Bene, grazie per la tua risposta !! – TheTom
Solo un'altra domanda sul comando: come posso accedere a security.content in un comando? $ user = $ this-> get ('security.context') -> getToken() -> getUser(); questo non funzionerà quindi mi sono bloccato di nuovo :( – TheTom
Forse perché '$ this-> get ('security.context') -> getToken() === null' – mykiwi