Symfony 3 - 查找 ID 的最佳实践

Symfony 3 - best practice for looking up ID

所以我有一个带有 createdBy 值(提交者的用户 ID)的投票 class,然后是一个列出投票中所有投票的控制器 table

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

我的树枝模板目前看起来有点像这样

        <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

创建一个简单的 twig 扩展,将整数转换为用户对象。显然,它通过在后台查询数据库来实现这一点,因此,启用 Doctrine 的二级缓存(假设您使用 Doctrine)不会每次都为用户对象访问数据库。当您致电时,它也会在控制器中提供帮助 $this->getUser()

Twig 扩展示例

<?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:确保即使在开发环境中也清除缓存以确保代码正常工作!