首页 > 解决方案 > 您不能在 laravel 中序列化或反序列化 PDO 实例

问题描述

我正在使用这样的默认 laravel 事件系统

use \Illuminate\Database\Connection;

class ExampleService {

private $connection;

    public function __construct(Connection $connection)
    {
        $this->connection = $connection;
    }
}

class ExampleEvent {

    private $service;

    public function __construc(ExampleService $service) {
        $this->service = $service;
    }
}


class ExampleListener implements ShouldQueue {

    public function handle(ExampleEvent $event) {

    }
}

这是我的自定义服务,我使用的是连接而不是 eloquent,每当我注入时,我都会将我的服务从事件解析到侦听器并将其放入队列中,我得到错误You cannot serialize or unserialize PDO instances。我希望我的听众一起工作,implements ShouldQeueue而不是创建不同的工作并从同一个听众分派

标签: phplaraveleventsserializationqueue

解决方案


将项目添加到队列中会使它们序列化。

Connection 包含一个 PDO 实例,但您无法序列化 PDO 实例,因此,您会收到该错误。

您应该实现__sleep 和 __wakeup方法以确保序列化正确发生,例如:

class ExampleService {

    private $connection;

    public function __construct(Connection $connection)
    {
        $this->connection = $connection;

    }

    public function __sleep() {
         return []; //Pass the names of the variables that should be serialised here
    }
    public function __wakeup() {
         //Since we can't serialize the connection we need to re-open it when we unserialise
         $this->connection = app()->make(Connection::class); 
    }
}

推荐阅读