Command Laravel

Asked

Viewed 364 times

0

I have a Queue class in Laravel 5.1 that does an insertion in mysql through a csv, but I can’t use Session in this class and I can’t even get the id of the user logged in by oauth 2.

How can I do this, at least use Session. Within the Handler method of the command class Session::get('id_logado') he returns me null.

  • Commands run on the command line are not able to capture the browser session. I think this is the confusion.

1 answer

1

When you add Jobs to an execution queue (Queue), you must pass all the required data. For example, if it’s a job to resize a user’s avatar, the information you need is the user’s id so you can load your template. Like when you are viewing a user’s profile page in the browser, you pass the necessary information in the URI request (for example, usuários/ profile/{id}).

Sessions will not work for queue tasks (Queue Jobs), because sessions are used to define states from browser requests, and Queue Jobs are run by the system.

So, continuing with example user avatar. You could pass the user id to the job, or pass the entire user template, however, if the job is late the status of this user may have changed in the meantime, then you would be working with inaccurate data.

This way, to add your job to the queue, use something like:

Queue::push('AvatarProcessor', [Session::get('id_logado')]);

When the job starts, load the user from the database and then forward it to other classes participating in the work. In this example I simulated sending the user id coming from the session as you wish. Imagining that the whole process starts with a browser user interface.

The following is an example of the avatar class retrieving information passed to the job.

class AvatarProcessor {

    public function fire($job, $data)
    {
        $user_id = $data[0]; // o id do usuário está no primeiro índice do array

        $user = User::find($user_id); // peça para o modelo carregar os dados do usuário baseado em seu id

        if ($user == null)
        {
            // caso o usuário não exista, trate corretamente com avisos, quem sabe, por email ao administrados
        }

        // Execute a lógica de manipulação de imagem necessária, um exemplo simples seria o código a seguir
        (new ImageManipulator)->resizeAvatar($user);

        $user->save(); // salve as alterações

        $job->delete(); // exclua o job ao concluir
    }

}

This response was based on and aided by the discussion on https://stackoverflow.com/questions/26548152/laravel-queues-persistent-variables-across-classes and for the documentation of Laravel’s http://laravel.com/docs/5.1/queues

Browser other questions tagged

You are not signed in. Login or sign up in order to post.