项目使用:
$dispatcher = new EventDispatcher(); $listener = new InventoryEventListener(); $dispatcher->addListener('add_stock_history.action', array($listener,'addStockHistory')); $event = new InventoryEvent($record, $this->entityManager, $targetUser); $dispatcher->dispatch('add_stock_history.action', $event);
//inventoryEvent.php
class InventoryEventListener { public function addStockHistory(InventoryEvent $event) { $record = $event->getRecord(); $entityManager = $event->getEntityManager(); $targetUser = $event->getTargetUser(); $operatorName = $targetUser->getName(); $inventoryQuantity = $record->getInventoryQuantity(); $operatorId = $targetUser->getId(); if ($record->getQuantity() != $inventoryQuantity) { $stockHistory = new StockHistory(); $date = date('Y-m-d'); $description = "[$date] $operatorName "; // 判断是盘存入库,还是盘存出库 if ($record->getQuantity() > $inventoryQuantity) { $stockHistory->setAction(StockHistory::INVENTORY_OUTBOUND); $description .= "盘存出库 "; } else { $stockHistory->setAction(StockHistory::INVENTORY_INBOUND); $description .= "盘存入库 "; } $quantity = $record->getQuantity(); $description .= $record->getGoodsName(); $description .= " "; $description .= $record->getMaterialSn(); $description .= " {$quantity} -> {$inventoryQuantity}"; $stockHistory->setQuantityBefore($record->getQuantity()); $stockHistory->setQuantityAfter($inventoryQuantity); $stockHistory->setMaterialId($record->getMaterialId()); $stockHistory->setOperatorId($operatorId); $stockHistory->setDescription($description); $entityManager->persist($stockHistory); } } }//inventoryEvent.php
class InventoryEvent extends Event { protected $record; protected $entityManager; protected $targetUser; public function __construct($record, ObjectManager $entityManager ,$targetUser) { $this->record = $record; $this->entityManager = $entityManager; $this->targetUser = $targetUser; } public function getRecord() { return $this->record; } public function getEntityManager() { return $this->entityManager; } public function getTargetUser() { return $this->targetUser; } }