【发布时间】:2012-03-24 12:42:51
【问题描述】:
我正在编写一个处理文章 (CRUD) 的服务。
持久层由 ArticleManager 处理,它执行 Repository 和 CRUD 操作。
现在我要实现两个属性:createdAt 和 >updatedAt
我现在的问题是我应该把它们放在哪里: 在实体中,在 ArticleManager 中,在其他什么地方?
最好的问候, 博多
啊,
我明白了,FOSUserBundle 使用 EventListener 处理此任务:
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Entity/UserListener.php
但是谢谢你的帮助:)
<?php
namespace LOC\ArticleBundle\Entity;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Events;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use LOC\ArticleBundle\Model\ArticleInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ArticleListener implements EventSubscriber
{
private $articleManager;
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getSubscribedEvents()
{
return array(
Events::prePersist,
Events::preUpdate,
);
}
public function prePersist(LifecycleEventArgs $args)
{
$article = $args->getEntity();
$article->setCreatedAt(new \DateTime());
$this->articleManager->updateArticle($article);
}
public function preUpdate(PreUpdateEventArgs $args)
{
$article = $args->getEntity();
$article->setUpdatedAt(new \DateTime());
$this->articleManager->updateArticle($article);
}
}
【问题讨论】:
标签: php symfony doctrine-orm entity