Laravel排队&跨类的持久变量

时间:2014-10-24 12:44:44

标签: php laravel laravel-4 queue

我正在潜入排队的世界和所有的善良,它打击了我:

当应用程序将任务推送到队列时,由于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);
    }
}

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

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

是不是有更清洁的方法呢?

2 个答案:

答案 0 :(得分:4)

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

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

返回用户头像示例。在排队作业时,您可以将用户的ID作为基元传递。您可以传递整个用户模型,但如果作业延迟了很长时间,那么该用户的状态可能会同时发生变化,因此您将使用不准确的数据。而且,正如您所提到的,并非所有对象都可以序列化,因此最好只将主键传递给作业,并且可以将其从数据库中删除。

因此排队工作:

Queue::push('AvatarProcessor', [$user->id]);

当您的工作被解雇时,将用户从数据库中删除,然后您就可以将其传递给其他类,就像在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
    }

}

答案 1 :(得分:0)

如maknz所述,数据需要显式传递到作业。但是在工作handle()方法中,您可以使用session()

public function handle()
{
    session()->put('query_id', 'H123214e890890');

然后可以在任何类中直接访问您的变量:

$query_id = session()->get('query_id')
相关问题