我的 Laravel 应用程序中有一个事件,对于特定记录,它超出了 Pusher 允许的最大限制(10240 字节)。 Laravel 序列化 Event 类上的每个公共(public)属性是否正确?如果是这样,我怀疑序列化模型不应超过 10kb 限制,但无论如何它都会失败。有什么方法可以减小数据内容的大小?
class PostChanged implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $post;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Post $post)
{
$this->post = $post;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('post-channel.'.$this->post->id);
}
public function broadcastWith()
{
$extra = [
'data' => $this->post->data,
];
return array_merge($this->post->toArray(), $extra);
}
}
产生:
The data content of this event exceeds the allowed maximum (10240 bytes).
See http://pusher.com/docs/server_api_guide/server_publishing_events for more info
最佳答案
方法一:在客户端解决
最可靠的方法是@ExohJosh 描述的:仅发送事件类型和 ID,以便客户端(很可能是 JavaScript)可以通过单独的 REST(或其他)API 获取更新的记录。
public function broadcastWith()
{
return [
'id' => $this->post->id,
];
}
方法 2:减少有效负载
另一种(更简单)的方法是只发送客户端所需的数据(你自己想出的那个@sarotnem)。但是,这种方法只有在您明确知道您提交的属性在任何情况下都不能超过 10KiB 限制的情况下才是安全的。这可以通过输入验证、对数据库列的限制或其他方式来确保。
选择此方法时,请务必将可能加载到模型上的任何关系的大小也包括到您的计算中。
Laravel 的 API Resources 是定义模型“外部表示”的一种简洁方法。 .他们可以让你的代码看起来像这样:
public function broadcastWith()
{
return [
'post' => new \App\Http\Resources\PostResource($this->post),
];
}
在哪里
App\Http\Resources\PostResource
可能:class PostResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'body' => $this->body,
];
}
}
关于Laravel 事件超出 Pusher 允许的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51147924/