Reputation: 143
Pre-note: I am learning Symfony from a Drupal 7 background.
I have created a custom model (although I think they are called services in Symfony from what I have read), and would like it to render an array via twig into a variable.
I found this link, and thought that this injection approach would do the trick: http://symfony.com/doc/2.8/service_container.html
Sadly, I and up with the below error:
Type error: Argument 1 passed to AppBundle\Model\Newsletter::__construct() must be an instance of AppBundle\Model\Twig_Environment, none given, called in /home/dan/working_files/symfony-playground/src/AppBundle/Controller/DefaultController.php on line 130
So, I am wondering what is an acceptable approach so I can use twig within my custom model/service/class?
If it is of use, here is some of my code for reference:
services.yml
services:
appbundle.newsletter:
class: AppBundle\Model\Newsletter
arguments: ['@twig']
src/AppBundle/Model/Newsletter.php
namespace AppBundle\Model;
class Newsletter
{
private $twig;
public function __construct(Twig_Environment $twig)
{
$this->twig = $twig;
}
}
Calling my model
$newsletter = new Newsletter();
Upvotes: 4
Views: 1799
Reputation: 2488
When you call $newsletter = new Newsletter();
you're not accessing the service through the dependency injection container, ignoring the service definition you did.
To leverage the DIC and have your dependencies like @twig
injected on your service, you should grab the service instance using the service container. To do that on a Symfony controller you can do it like this:
$newsletter = $this->get('appbundle.newsletter');
@twig
is gonna be injected in your service as defined on the yaml file and it is shared between every place you use your service again through the container.
Upvotes: 0
Reputation: 35963
try to change twig with EngineInterface like this:
services:
appbundle.newsletter:
class: AppBundle\Model\Newsletter
arguments: ['@templating']
And
namespace AppBundle\Model;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
class Newsletter
{
private $twig;
public function __construct(EngineInterface $templating)
{
$this->twig = $templating;
}
}
After you need o call the service:
$this->get('service_name');
Upvotes: 2