我在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.
}
}
我感谢所有答复,对问题的反馈和建议,以寻求更好的解决方法。
现在,我没有使用侦听器,而是尝试了Laravel Pipeline,这是一种将数据通过不同管道传递并过滤的很好方法。本文对理解它非常有帮助https://jeffochoa.me/understanding-laravel-pipelines
这是代码的最终版本,以及我如何使用Laravel Pipeline:
节点:Page.php
<?php declare(strict_types=1);
namespace Vendor\Package\Nodes;
class Page extends ReactPage
{
public function toArray() : array
{
$data = parent::toArray();
$pipes = [
AppendFlashMessage::class,
RemoveEmptyLayoutNode::class
];
// Filter data through the pipelines.
$data = app(Pipeline::class)
->send($data)
->through($pipes)
->via('filter')
->then(function($data) {
return $data;
});
return $data;
}
}
管道:AppendFlashMessage.php
<?php declare(strict_types=1);
namespace Vendor\Package\Pipeline;
use Closure;
class AppendFlashMessage
{
public function filter(array $data, Closure $next) : array
{
// step 1: pull the errors from session.
$errors = [
'type' => 'error',
'message' => 'Invalid User Name'
];
$data['messages'] = $errors;
return $next($data);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句