【发布时间】:2019-11-05 13:04:59
【问题描述】:
我有点困惑应该在哪里实现事件订阅器(实际上,我什至不确定是否应该使用实体监听器)。
所以,我有这个实体叫ServiceDoctrineEntity,这个实体有很多存储设备:
class ServiceDoctrineEntity {
/**
* One Service has many storage devices.
*
* @OneToMany(targetEntity="ServiceStorageDevicesDoctrineEntity", mappedBy="service", cascade={"all"})
* @OrderBy({"order" = "ASC"})
* @var ServiceStorageDevicesDoctrineEntity $storage_devices Description.
*/
private $storage_devices;
}
每个存储设备都有自己的“存储空间/价值”
class ServiceStorageDevicesDoctrineEntity {
/**
* @Column(type="bigint", nullable=true, options={"comment":"The normalised value, calculated from $amount * $unit."})
* @var int $value The normalised value, calculated from $amount * $unit.
*/
private $value;
}
我的问题是,我应该运行一个计算逻辑,该逻辑将在每次存储设备发生变化时触发(添加/删除新存储设备,或更改存储空间等)。
- 我需要计算此服务拥有的“存储设备”总数。
- 汇总或求和每个存储设备的总“值”
这些“摘要”将保存在一个名为:ServiceStorageSummaryDoctrineEntity的实体上
class ServiceStorageSummaryDoctrineEntity {
/**
* One Service Support type has One Service.
*
* @OneToOne(targetEntity="ServiceDoctrineEntity", inversedBy="storage_summary")
* @JoinColumn(name="service_id", referencedColumnName="id")
*/
private $service;
/**
* @Column(type="bigint", nullable=true, options={"default":0, "comment":"The total value (normalised) of storage space."})
* @var integer $total_value The total value (normalised) of storage space.
*/
private $total_value;
/**
* @Column(type="integer", nullable=true, options={"default":0, "comment":"The total amount of storage devices."})
* @var integer $device_count The total amount of storage devices.
*/
private $device_count;
}
我尝试为此编写一个EventSubscriber 类来监听onFlush 事件:
class ServiceStorageDevicesEventListener implements EventSubscriber {
/**
* Returns an array of events this subscriber wants to listen to.
*
* @return string[]
*/
public function getSubscribedEvents() {
return array(
Events::onFlush,
);
}
public function onFlush( OnFlushEventArgs $eventArgs ) {
$em = $eventArgs->getEntityManager();
$uow = $em->getUnitOfWork();
foreach ( $uow->getScheduledEntityInsertions() as $entity ) {
// Should I run the computation here?
// Which entity should I be listening to? `ServiceDoctrineEntity` or `ServiceStorageSummaryDoctrineEntity`?
}
foreach ( $uow->getScheduledEntityUpdates() as $entity ) {
// Should I run the computation here?
// Which entity should I be listening to? `ServiceDoctrineEntity` or `ServiceStorageSummaryDoctrineEntity`?
}
foreach ( $uow->getScheduledEntityDeletions() as $entity ) {
// Should I run the computation here?
// Which entity should I be listening to? `ServiceDoctrineEntity` or `ServiceStorageSummaryDoctrineEntity`?
}
}
}
但我不确定如何继续:
- 我是否正确使用事件订阅者?
- 我是否有权收听
onFlush事件 -
我应该列出哪个实体:
(a)
ServiceDoctrine实体并循环遍历每个存储设备?(b) 或
ServiceStorageDevicesDoctrineEntity但这不意味着计算逻辑将针对每个存储设备更改运行?
【问题讨论】:
标签: php symfony doctrine-orm doctrine