sar*_*nem 5 events serialization limit laravel pusher
我的 Laravel 应用程序中有一个事件,对于特定记录,它超过了 Pusher 允许的最大限制(10240 字节)。Laravel 序列化 Event 类上的每个公共属性是否正确?如果是这样,我怀疑序列化模型不应超过 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);
}
}
Run Code Online (Sandbox Code Playgroud)
产生:
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
Run Code Online (Sandbox Code Playgroud)
方法一:客户端解决
最可靠的方法是 @ExohJosh 所描述的:仅发送事件类型和 ID,以便客户端(很可能是 JavaScript)可以通过单独的 REST(或其他)API 获取更新的记录。
public function broadcastWith()
{
return [
'id' => $this->post->id,
];
}
Run Code Online (Sandbox Code Playgroud)
方法 2:减少有效负载
另一种(更简单)的方法是仅发送客户端所需的数据(您自己找到的数据@sarotnem)。然而,只有当您明确知道您提交的属性在任何情况下都不能超过 10KiB 限制时,这种方法才是安全的。这可以通过输入验证、数据库列限制或其他方式来确保。
选择此方法时,请务必将可能加载到模型上的任何关系的大小也包括在计算中。
Laravel 的API 资源是定义模型“外部表示”的一种巧妙方法。他们可以让你的代码看起来像这样:
public function broadcastWith()
{
return [
'post' => new \App\Http\Resources\PostResource($this->post),
];
}
Run Code Online (Sandbox Code Playgroud)
哪里App\Http\Resources\PostResource可能是:
class PostResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'body' => $this->body,
];
}
}
Run Code Online (Sandbox Code Playgroud)