I need to call doctrine and logged in user in symfony extensions.
this is my service yml
twig.extension.app:
class: AppBundle\Twig\AppExtension
arguments:
$doctrine : '@doctrine'
$context : '@security.context'
tags:
- { name: twig.extension }
twig.extension.auth:
class: AppBundle\Twig\AuthExtension
arguments:
$doctrine : '@doctrine'
$context : '@security.context'
tags:
- { name: twig.extension }
in my case, i devide it to be two extensions.
and this is my extensions :
<?php
namespace AppBundle\Twig;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Component\Security\Core\Security;
class AuthExtension extends \Twig_Extension
{
protected $doctrine;
protected $context;
public function __construct(RegistryInterface $doctrine, Security $context)
{
$this->doctrine = $doctrine;
$this->context = $context;
}
}
but I got error :
[Symfony\Component\DependencyInjection\Exception\AutowiringFailedException]
Cannot autowire service "AppBundle\Twig\AppExtension": argument "$context" of method "__construct()" references class "Symfony\Component\Security\Core\Security" but no such service exists. It cannot be auto-registered because it is from a different root namespace.
how to solve this, in condition i need doctrine and also current logged in user?
If you have a Twig Extension, you should add to it into services.yml
. This is a sample;
twig.json_decode:
class: DashboardBundle\Twig\Extension\JsonDecode
tags:
- { name: twig.extension }
If you need another object, you should send to objects;
twig.json_decode:
class: DashboardBundle\Twig\Extension\JsonDecode
arguments: [ "@doctrine_object_name", "@security_object_name" ]
tags:
- { name: twig.extension }
Another way, you can send service_container
object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.