Symfony2:哪里有slug和timestamp方法?

bod*_*ser 2 php entity symfony doctrine-orm

我正在编写一个处理文章的服务(CRUD).

持久层由ArticleManager>处理,它执行Repository和CRUD操作.

现在我想实现两个属性:createdAt和> updatedAt

我现在的问题是放置它们:在实体中,在ArticleManager中,在其他地方?

最诚挚的问候,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);
}
}
Run Code Online (Sandbox Code Playgroud)

Sgo*_*kes 11

好吧,有一个包这样的东西,DoctrineExtensionsBundle.它有Timestampable和slugable.

如果你想自己做,这个地方肯定在实体本身,因为你不想在你的控制器中乱七八糟.以下是我如何使用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();
    }

    // ...

}
Run Code Online (Sandbox Code Playgroud)

至于我决定不使用Bundle:当symfony2被释放为稳定时,这个包不存在(或者它不稳定,我不记得了)所以我开始自己做,如下图所示.由于它的开销很小,我一直这样做,从来没有觉得需要改变它.如果您需要Slugable或想要保持简单,请尝试捆绑!