尝试调用类“App \ Twig \ AppExtension”的名为“getDoctrine”的未定义方法

I am new to learning symfony4. I have a problem to use the doctrine in the twig extension. How to use the doctrine query in twig extension.

please help me how to configure the service for this code


namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class AppExtension extends AbstractExtension
{
     public function getFilters(): array
    {
        return [
            // If your filter generates SAFE HTML, you should add a third
            // parameter: ['is_safe' => ['html']]
            // Reference: https://twig.symfony.com/doc/2.x/advanced.html#automatic-escaping
            new TwigFilter('filter_name', [$this, 'doSomething']),
        ];
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('followed', [$this, 'doSomething']),
        ];
    }

    public function doSomething($id, $admin)
    {
        // ...
        $follower = $this->getDoctrine()->getRepository(Follower::class)->findAll();
        foreach( $follower as $value ){
            if($value['user']==$admin && $value['followed_user']==$id) return false;
        }
        return true;
    }
}

Here is my twig function code

{% if followed(users.id, app.user.id) %}

The error occurs when I run the page Attempted to call an undefined method named "getDoctrine" of class "App\Twig\AppExtension".

Please help me to provide the solution

getDoctine is a function defined in AbstractController (or ControllerTrait to be precise) and is not available on Twig extensions. You need to inject the doctrine service into your class. Most of your code omitted for brevity:

use Doctrine\Common\Persistence\ManagerRegistry;

class AppExtension extends AbstractExtension
{
    private $em;

    public function __construct(ManagerRegistry $registry)
    {
        $this->em = $registry;
    }

    public function doSomething($id, $admin)
    {
        $follower = $this->em->getRepository(Follower::class)->findAll();
        // ...
    }
}

I used this and now the problem solved

    use Doctrine\Common\Persistence\ManagerRegistry;

    public function doSomething($id, $admin)
    {
        // ...
        $follower = $this->em->getRepository(Follower::class)->findBy([
            'followed_user' => $id,
            'user' => $admin
        ]);

        if(sizeof($follower)>0) return false;
        else return true;
    }