- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
I am coding a service which will handle articles (CRUD).
The persistence layer is handles by an ArticleManager >which does Repository and CRUD actions.
Now I want to implement two attributes: createdAt and >updatedAt
My question is now where I should place them:In the entity, in the ArticleManager, somewhere else?
Best Regards,Bodo
啊,
我明白了,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);
}
}
最佳答案
好吧,这些东西有一个包,DoctrineExtensionsBundle .它具有 Timestampable 和 slugable。
如果你想自己做,这个地方肯定在实体本身,因为你不想在你的 Controller 中乱七八糟。这是我如何使用 Timestampable,因为我不使用 DoctrineExtensionsBundle:
/**
* @ORM\Entity
* @ORM\Table(name="entity")
* @ORM\HasLifecycleCallbacks
*/
class Entity {
// ...
/**
* @ORM\Column(name="created_at", type="datetime", nullable=false)
*/
protected $createdAt;
/**
* @ORM\Column(name="updated_at", type="datetime", nullable=false)
*/
protected $updatedAt;
/**
* @ORM\prePersist
*/
public function prePersist() {
$this->createdAt = new \DateTime();
$this->updatedAt = new \DateTime();
}
/**
* @ORM\preUpdate
*/
public function preUpdate() {
$this->updatedAt = new \DateTime();
}
// ...
}
至于我决定不使用 Bundle:当 symfony2 作为稳定版发布时,这个 bundle 不存在(或者它不稳定,我不记得了)所以我开始自己做,如图所示以下。因为它的开销很小,所以我一直这样做,从不觉得有必要改变它。如果您需要 Slugable 或希望保持简单,请尝试 bundle !
关于php - Symfony2 : Where place slug and timestamp methods?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9851865/
我是一名优秀的程序员,十分优秀!