Symfony 3 - 查找ID的最佳实践

时间:2016-10-19 20:42:43

标签: php symfony fosuserbundle

所以我有一个带有createdBy值的poll类(提交它的人的userID),然后是一个列出poll表中所有民意调查的控制器

    public function indexAction()
{
    $entityManager = $this->getDoctrine()->getManager();
    $posts = $entityManager->getRepository(Poll::class)->findBy([], ['createdDate' => 'DESC']);

    return $this->render('poll/admin/index.html.twig', ['posts' => $posts]);
}

我的twig模板在momemt

看起来有点像这样
        <tbody>
    {% for poll in posts %}
        <tr id="poll_{{ poll.id }}">
            <td> {{ poll.title }}</td>
            <td>{{ poll.createdBy }}</td>
            <td>etc</td>
            <td>etc</td>
            <td>etc</td>
        </tr>
    {% endfor %}
    </tbody>

如果我想显示实际的用户名而不是createdBy ID,那么最佳做法是什么?我正在使用FOSUserBundle

1 个答案:

答案 0 :(得分:1)

创建一个简单的枝条扩展,将整数转换为用户对象。显然,它通过在后台查询数据库来实现这一点,因此,启用Doctrine的二级缓存(假设您使用Doctrine)不会每次都为用户Object命中DB。当你打电话时,它也会对控制器有所帮助 $这 - &GT;的getUser()

示例树枝扩展

<?php

namespace AppBundle\Twig;

use Twig_Extension;
use Twig_SimpleFilter;
use Doctrine\ORM\EntityManager;
use JMS\DiExtraBundle\Annotation\Tag;
use JMS\DiExtraBundle\Annotation\Inject;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Service;

/**
 * @Service("app.twig_extension_hydrate_user" , public=false)
 * @Tag("twig.extension")
 */
class HydrateUserExtension extends Twig_Extension
{
    protected $em;

    /**
     * @InjectParams({
     *     "em" = @Inject("doctrine.orm.entity_manager")
     * })
     */
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * @inheritdoc
     */
    public function getName()
    {
        return 'hydrate_user_extension';
    }

    public function getFilters()
    {
        return array(
            new Twig_SimpleFilter('hydrateUser', array($this, 'hydrateUserFilter')),
        );
    }

    public function hydrateUserFilter($user_id)
    {
        $em = $this->em;
        $user = $em
            ->getRepository('AppBundle:Users')
            ->queryUserById($user_id);
        return $user;
    }

}

然后在你的例子中的Twig模板中

<tbody>
{% for poll in posts %}
<tr id="poll_{{ poll.id }}">
    <td> {{ poll.title }}</td>
    <td>{{ poll.createdBy|hydrateUser.username }}</td>
    <td>etc</td>
    <td>etc</td>
    <td>etc</td>
</tr>
{% endfor %}
</tbody>

PS:确保您在开发环境中清除缓存,以确保代码正常工作!