symfony2中的EventDispatcher的项目使用

本文介绍了一种通过事件监听机制实现库存变动记录的方法。当库存发生变化时,系统会触发事件,由专门的监听器处理这些事件,并根据变化情况创建库存历史记录。此过程涉及事件分发器、监听器及事件对象的使用。

项目使用:

$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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值