在 symfony 控制器上过滤实体字段

filter entity fields on symfony controller

如何在我的控制器上选择(过滤)我想要(或不想)将哪些字段传递到我的前端?

我的控制器:

/**
 * @Route("/", name="dashboard")
 */
public function index()
{

    $aniversariantes = $this->getDoctrine()->getRepository(Usuario::class)->aniversariantes();

    return $this->render('dashboard/index.html.twig', [
        'controller_name' => 'DashboardController',
        'aniversariantes' => $aniversariantes
    ]);
}

我的存储库:

/**
 * @return []
 */
public function aniversariantes(): array
{
 $qb = $this->createQueryBuilder('u')
    ->andWhere('u.ativo = 1')
    ->andwhere('extract(month from u.dtNascimento) = :hoje')
    ->setParameter('hoje', date('m'))
    ->getQuery();

    return $qb->execute();
}

从实体转储:

例如,我不想传递“密码”字段怎么办?

如果您只是想防止某些字段被转储,了解

会很有用

Internally, Twig uses the PHP var_dump function.

https://twig.symfony.com/doc/2.x/functions/dump.html

这意味着您可以在您的实体中定义 PHP 魔法方法 __debugInfo

This method is called by var_dump() when dumping an object to get the properties that should be shown. If the method isn't defined on an object, then all public, protected and private properties will be shown.

https://www.php.net/manual/en/language.oop5.magic.php#object.debuginfo

所以在你的实体中做这样的事情:

class Usuario {
    ...

    public function __debugInfo() {
        return [
            // add index for every field you want to be dumped 
            // assign/manipulate values the way you want it dumped
            'id' => $this->id,
            'nome' => $this->nome,
            'dtCadastro' => $this->dtCadastro->format('Y-m-d H:i:s'),
        ];
    }

    ...
}