首页 > 解决方案 > 试图调用类“App\Twig\AppExtension”的名为“getDoctrine”的未定义方法

问题描述

我是学习 symfony4 的新手。我在树枝扩展中使用该学说时遇到问题。如何在树枝扩展中使用教义查询。

请帮助我如何为此代码配置服务


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;
    }
}

这是我的树枝功能代码

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

当我运行 试图调用类“App\Twig\AppExtension”的名为“getDoctrine”的未定义方法的页面时发生错误。

请帮我提供解决方案

标签: phpdoctrine-ormdoctrinesymfony4

解决方案


我用了这个,现在问题解决了

    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;
    }

推荐阅读