我有一段重复的代码,将在我的 Symfony2 项目中的多个实体中使用,因此应用某种 DRY 就可以了,当然如果可能的话,我正在考虑PHP 特性 http://php.net/manual/en/language.oop5.traits.php.
private static $preDeletedEntities;// static array that will contain entities due to deletion.
private static $deletedEntities;// static array that will contain entities that were deleted (well, at least the SQL was thrown).
/**
* This callback will be called on the preRemove event
* @ORM\PreRemove
*/
public function entityDueToDeletion()
{
// This entity is due to be deleted though not deleted yet.
self::$preDeletedEntities[] = $this->getId();
}
/**
* This callback will be called in the postRemove event
* @ORM\PostRemove
*/
public function entityDeleted()
{
// The SQL to delete the entity has been issued. Could fail and trigger the rollback in which case the id doesn't get stored in the array.
self::$deletedEntities[] = $this->getId();
}
public static function getDeletedEntities()
{
return array_slice(self::$preDeletedEntities, 0, count(self::$deletedEntities));
}
public static function getNotDeletedEntities()
{
return array_slice(self::$preDeletedEntities, count(self::$deletedEntities)+1, count(self::$preDeletedEntities));
}
public static function getFailedToDeleteEntity()
{
if(count(self::$preDeletedEntities) == count(self::$deletedEntities)) {
return NULL; // Everything went ok
}
return self::$preDeletedEntities[count(self::$deletedEntities)]; // We return the id of the entity that failed.
}
public static function prepareArrays()
{
self::$preDeletedEntities = array();
self::$deletedEntities = array();
}
这是我想到的代码:
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\HasLifecycleCallbacks()
*/
trait DeleteLifeCycleCallbacksTrait
{
// write things here
}
但是注释会应用于实体吗?可以吗?为了避免不重复代码,你会做什么?
编辑:试图找到最佳方法
有一些想法来自@Cerad用户,因为正如文档所说生命周期事件监听器比简单的生命周期回调更强大然后我就开始和他们一起玩。
那么,首先,我们这样做的目的Lifecycle Callbacks|Listener|Suscribers
将存储每个持久对象的 ID,以便我可以以某种方式获取它并从控制器发送回视图。作为一个简单的视觉示例,假设我从视图向控制器发送这个值数组(1, 2, 3, 4, 5)
由于某些 X 原因,只有 1 ,4 和 5 被持久化(意味着从数据库中完全删除)到数据库,对吗?
还可以说我将在以下位置使用事件侦听器Producto
实体。因此,如果没有测试而只是从示例中获取代码,则代码应该是这样的Listener
:
use Doctrine\ORM\Event\LifecycleEventArgs;
use Entity\Producto;
class StoreDeletedIds
{
private $deletedItems = [];
public function postDelete(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$entityManager = $args->getEntityManager();
if ($entity instanceof Producto) {
array_push($deletedItems, $entity->getId());
}
}
}
我对此的疑问是:
- 上面的代码好还是不好?
- Is
$deletedItems
每次 Doctrine 调用监听器时都会清理?
- 我该如何返回
$deletedItems
为了在控制器上捕获它并将其发送回视图?
- 我需要定义订阅者吗?为什么?
这对我来说是新主题,所以我需要一些建议