Php Symfony2:获取实体类内的security.context
是否可以在实体类中获取Php Symfony2:获取实体类内的security.context,php,symfony,encapsulation,Php,Symfony,Encapsulation,是否可以在实体类中获取security.context 我知道下面的方法行不通。我不知道如何实现$user部分 /** * Set createdAt * * @ORM\PrePersist */ public function setCreatedAt() { $user = $this->get('security.context')->getToken()->getUser(); $this->owner = $user->getId
security.context
我知道下面的方法行不通。我不知道如何实现$user
部分
/**
* Set createdAt
*
* @ORM\PrePersist
*/
public function setCreatedAt()
{
$user = $this->get('security.context')->getToken()->getUser();
$this->owner = $user->getId();
$this->createdAt = new \DateTime();
$this->updatedAt = new \DateTime();
}
事实上,这是错误的
保持简单,创建实体时是否要设置实体的所有者?将其传递给实体构造函数并在那里设置
旁注我建议使用prePersist和preUpdate生命周期回调来处理实体时间戳。这个库(php 5.4+)提供了一组非常简单的工具来实现这些功能:用于日期时间:
对于时间戳,您最好使用@hasLifeCycleCallback注释和一些标记为@prePersist和@preUpdate的附加方法。
对于created,您甚至可以在_构造函数本身中执行它
请注意,必须对$updatedAt属性使用@preUpdate,@prePersist仅适用于新实体
如果你有很多需要这个的实体,你可以考虑一个Trime2侦听器来防止重复的代码。 对于所有权属性:
如果您总是想将实体的所有权设置为“当前登录的用户”,那么最好使用Doctrine2侦听器或订阅服务器。 这样,您就不必将此逻辑添加到控制器中,也不必添加到需要创建实体的任何位置 创建一个记录在案的侦听器服务,确保它使用构造函数获取安全上下文。 将其设置为事件onFlush,这样您就可以在实际保存之前调整实体。这是处理这类事情的最佳事件 确保您遵循原则文档的onFlush一章中的脚注,否则原则将不会接受最后一分钟的更改 您的听众可能看起来像:class FlushExampleListener
{
public function onFlush(OnFlushEventArgs $eventArgs)
{
$em = $eventArgs->getEntityManager();
$uow = $em->getUnitOfWork();
foreach ($uow->getScheduledEntityInsertions() as $entity) {
if ($entity instanceof YourClass) {
// change owner
$entity->setOwner($this->securityContext->getToken()->getUser());
// tell doctrine you changed it
$uow->recomputeSingleEntityChangeSet($em->getClassMetadata(get_class($entity)), $entity);
}
}
foreach ($uow->getScheduledEntityUpdates() as $entity) {
if ($entity instanceof YourClass) {
// change owner
$entity->setOwner($this->securityContext->getToken()->getUser());
// tell doctrine you changed it
$uow->recomputeSingleEntityChangeSet($em->getClassMetadata(get_class($entity)), $entity);
}
}
}
}
请注意,这不会检查用户是否实际登录…基本上不会。可以通过全局访问容器,但非常不鼓励。将用户/所有者作为参数传递给函数。