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

问题描述

如何在控制器上选择(过滤)我想要(或不希望)传递给前端的字段?

我的控制器:

/**
 * @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();
}

从实体转储:

enter image description here

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

解决方法

如果您只是想防止某些字段被转储,了解这一点很有用

在内部,Twig使用PHP var_dump函数。

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

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

在转储对象以获取应显示的属性时,此方法由var_dump()调用。如果未在对象上定义该方法,则将显示所有公共,受保护和私有属性。

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

    ...
}