我是不熟悉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”的未定义方法。
请帮助我提供解决方案
答案 0 :(得分:0)
getDoctine
是在AbstractController
中定义的功能(确切地说是ControllerTrait
),在Twig扩展名中不可用。您需要将doctrine
服务注入您的班级。为简洁起见,省略了大多数代码:
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();
// ...
}
}
答案 1 :(得分:0)
我用了这个,现在问题解决了
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;
}