RenderView in My service

You are correct about renderView(), it's only a shortcut for Controllers. When using a service class and inject the templating service, all you have to do is change your function to render() instead. So instead of

return $this->renderView('Hello/index.html.twig', array('name' => $name));

you would use

return $this->render('Hello/index.html.twig', array('name' => $name));

Update from Olivia's response:

If you are getting circular reference errors, the only way around them is to inject the whole container. It's not considered best practice but it sometimes cannot be avoided. When I have to resort to this, I still set my class variables in the constructor so I can act as if they were injected directly. So I will do:

use Symfony\Component\DependencyInjection\ContainerInterface;

class MyClass()
{
    private $mailer;
    private $templating;

    public function __construct(ContainerInterface $container)
    {
        $this->mailer = $container->get('mailer');
        $this->templating = $container->get('templating');
    }
    // rest of class will use these services as if injected directly
}

Side note, I just tested my own standalone service in Symfony 2.5 and did not receive a circular reference by injecting the mailer and templating services directly.


Using constructor dependency injection (tested with Symfony 3.4):

class MyService
{
    private $mailer;
    private $templating;

    public function __construct(\Swift_Mailer $mailer, \Twig_Environment $templating)
    {
        $this->mailer     = $mailer;
        $this->templating = $templating;
    }

    public function sendEmail()
    {
        $message = $this->templating->render('emails/registration.html.twig');

        // ...
    }
}

No need to configure arguments.


This works on Symfony +4.2, assuming your application's namespace is App and your mailer class service is named EmailService.

On your Service class:

// ...

private $mailer;
private $templating;

public function __construct( \Swift_Mailer $mailer, \Twig\Environment $templating )
{
    $this->mailer = $mailer;
    $this->templating = $templating;
}

public function sendEmailRegistration()
{
    $message = $this->templating->render('emails/registration.html.twig');

    // ...
}

// ...

On your services.yaml

services:
  email_service:
    class: App\Service\EmailService
    arguments: ['@swiftmailer.mailer.default', '@twig']

Tags:

Php

Symfony