如果事件使用可选参数,你可以使它们在构造函数中可选。
use Symfony\Component\EventDispatcher\Event;
final class PowerPlantEvent extends Event
{
/**
* @var PowerPlantAction
*/
private $powerPlantAction;
/**
* @var \DateTime
*/
private $startDate;
/**
* @var \DateTime
*/
private $endDate;
/**
* @var int
*/
private $measurement;
/**
* @var string
*/
private $field;
public function __construct(
$powerPlantAction,
$startDate = null,
$endDate = null,
$measurement = null,
$field = null
) {
$this->powerPlantAction = $powerPlantAction;
$this->startDate = $startDate;
$this->endDate = $endDate;
$this->measurement = $measurement;
$this->field = $field;
}
public function getPowerPlantAction()
{
return $this->powerPlantAction;
}
public function getStartDate()
{
return $this->startDate;
}
public function getEndDate()
{
return $this->endDate;
}
public function getMeasurement()
{
return $this->measurement;
}
public function getField()
{
return $this->field;
}
}
然后派遣这样的:
$this->eventDispatcher->dispatch(
Events::POWERPLANT_GET_DATA,
new PowerPlantEvent($this->getPowerPlantAction($id))
);
或者:
$this->eventDispatcher->dispatch(
Events::POWERPLANT_GET_DATA,
new PowerPlantEvent(
$this->getPowerPlantAction($id),
$startDate,
$endDate,
$measurement,
$field
)
);
在您的用户只需使用这些干将:
public function onPowerPlantGetData(PowerPlantEvent $powerPlantEvent)
{
$powerPlantEvent->getStartDate();
// ...
}
我可以dispach事件,如:$调度 - > dispatch(Events :: POWERPLANT_GET_DATA,new Powe rPlantEvent($ this-> getPowerPlantAction($ id)),$ startDate,$ endDate,$ measurement,$ field);或者有其他方法吗? – sanof