gpt4 book ai didi

php - Symfony2 : Where place slug and timestamp methods?

转载 作者:行者123 更新时间:2023-12-02 05:44:06 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com