我正在创建API,我需要根据操作类型显示实体中的数据。例如,我有用户和他的可见性偏好(隐藏/显示其他人的名字)。这样做:
<?php
// entity
public function getSurname()
{
$visibility = $this->getVisibility();
if($visibility['name'] == 0)
return $this->surname;
return '';
}
没问题,但是如果用户已登录,我想向他显示他的名字,例如,在编辑帐户中。 我认为最好的方法是在从数据库中获取记录时编辑记录,但是如何在doctrine对象上进行编辑?
<?php
//controller
$user = $this->getDoctrine()->getRepository('AcmeDemoBundle:User')->findOneById($id);
$user = $this->getVisibility();
if($user != $this->getUser() && $visibility['name'] == 0)
$user->setSurname(''); //but this save this to DB, not to "view"
更新
不幸的是(或者我做错了)我的问题无法通过Snake回答解决,因为当我执行此代码时:
<?php
$user = $this->getDoctrine()->getRepository('AcmeDemoBundle')-findOneById($id);
return array(
self::USER => $user
);
在我的API响应中,实体修改不起作用,因为我认为这是直接从DB获取记录?我需要像上面的代码一样返回整个对象。
UPDATE2
我找到了解决方法
<?php
// entity
/**
* @ORM\PostLoad
*/
public function postLoad() {
$this->surname = $this->getSurname();
}
然后我就可以返回完整的$ user对象
答案 0 :(得分:0)
如果您想显示姓氏取决于可见性,您可以添加Symfony\Component\Security\Core\User\EquatableInterface
并编辑您的功能:
// entity
public function getSurname(Acme\DemoBundle\User $user = null)
{
// Nothing to compare or is the owner
if( !is_null( $user ) && $this->isEqualTo($user) ){
return $this->surname;
}
// else...
$visibility = $this->getVisibility();
if($visibility['name'] == 0)
return $this->surname;
return '';
}
在你的控制器中你只需要得到姓氏:
//controller
$user = $this->getDoctrine()->getRepository('AcmeDemoBundle:User')->findOneById($id);
// If the user is the owner, show the surname, otherwise it shows the surname depends of visibility
$surname = $user->getSurname( $this->getUser() );
此外,您可以在控制器中执行逻辑(检查是否是同一个用户并获得可见性......)。
我建议你也阅读ACL。