Laravel 队列和跨类的持久变量

Mys*_*yos 2 php queue laravel laravel-4

在那里,我潜入了队列的世界及其所有美好之处,这让我感到震惊:

由于 Laravel 对信息进行序列化,当应用程序将任务推送到队列时,会话数据会丢失。

了解了如何将数据发送到队列后,仍然存在一个问题:

鉴于队列将信息推送到单个类,

在此任务的整个持续时间内,我如何使该信息在其他类中持久化(例如会话)?

编码示例:

//Case where the user object is needed by each class
class queueme {
    ...
    //function called by queue
    function atask($job,$data) 
    {
         //Does xyz
         if(isset($data['user_id'])
         {
              //Push user_id to another class
              anotherclass::anothertask($data['user_id']);
         }
    }
}

class anotherclass {
    ...
    function anothertask($user_id)
    {
         //Does abc
         //Yup, that anotherofanother class needs user_id, we send it again.
         anotherofanotherclass::yetanothertask($user_id);
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码说明了我的问题。

如果我的课程需要此信息,我是否必须传递$user_idUser对象?

没有更干净的方法吗?

mak*_*knz 5

当你排队一个作业时,你应该传递作业所需的所有数据来完成它的工作。因此,如果调整用户头像大小是一项工作,所需的必要信息是用户的主键,以便我们可以在工作中提取他们的模型。就像您在浏览器中查看用户的个人资料页面一样,请求 URI 中可能会提供必要的信息(用户的主键)(例如 users/profile/{id})。

会话不适用于队列作业,因为会话用于从浏览器请求传递状态,而队列作业由系统运行,因此它们根本不存在。但这很好,因为每个类都负责查找数据并不是一个好习惯。处理请求的类(HTTP 请求的控制器,或队列作业的作业类)可以接受输入并查找模型等,但此后的每次调用都可以传递这些对象。

回到用户头像示例。在排队作业时,您将用户的 ID 作为原语传递。您可以传递整个用户模型,但是如果作业延迟很长时间,该用户的状态可能会同时发生变化,因此您将使用不准确的数据。而且,正如您所提到的,并非所有对象都可以序列化,因此最好将主键传递给作业,然后它可以从数据库中重新获取它。

所以排队你的工作:

Queue::push('AvatarProcessor', [$user->id]);
Run Code Online (Sandbox Code Playgroud)

当您的工作被解雇时,从数据库中提取新用户,然后您就可以将其传递给其他类,就像在 Web 请求或任何其他场景中一样。

class AvatarProcessor {

    public function fire($job, $data)
    {
        $user_id = $data[0]; // the user id is the first item in the array

        $user = User::find($user_id); // re-pull the model from the database

        if ($user == null)
        {
            // handle the possibility the user has been deleted since
            // the job was pushed
        }

        // Do any work you like here. For an image manipulation example,
        // we'll probably do some work and upload a new version of the avatar
        // to a cloud provider like Amazon S3, and change the URL to the avatar
        // on the user object. The method accepts the user model, it doesn't need
        // to reconstruct the model again
        (new ImageManipulator)->resizeAvatar($user);

        $user->save(); // save the changes the image manipulator made

        $job->delete(); // delete the job since we've completed it
    }

}
Run Code Online (Sandbox Code Playgroud)