我在 Laravel 应用程序中有一个数组,我想在 Laravel 侦听器中修改它。PHP 默认按值传递一个数组,但是,Laravel 事件及其侦听器的工作方式我无法修改原始变量。有没有比我在下面做的更好的方法?
从中触发事件的模型。
型号:Event.php
namespace Vendor\Package\Models
use Vendor\Package\Events\PageNodeArrayAfter;
use Event;
class Page
{
public function toArray()
{
$data = [];
// do something with the data.
Event::fire(new PageNodeToArrayAfter($data))
// The data should be modified by a listener when I use it here.
}
}
事件:PageNodeToArrayAfter.php
namespace Vendor\Package\Events;
class PageNodeToArrayAfter
{
/**
* Props to be sent to the view
* @var array $data
*/
protected $data = [];
/**
* @param array $data
*
*/
public function __construct(array &$data)
{
$this->data = $data;
}
public function getData()
{
return $this->data;
}
}
监听器:FlashMessagesListner.php
namespace Vendor\Package\Listeners;
class FlashMessagesListner
{
protected $data = [];
public function handle(PageNodeToArrayAfter $event)
{
$this->data = $event->getData();
// The problem here is the $data is no logner a reference here.
}
}
富国沪深