Skip to content

Instantly share code, notes, and snippets.

@carltondickson
Created June 6, 2018 16:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save carltondickson/81f0b59c9c480108eedd6e18ac2790d4 to your computer and use it in GitHub Desktop.
Laravel - Jobs - Sessions
<?php
# Dispatch the following job from multiple tinker instances will see session never gets updated.
# Using sessions in jobs is bad idea.
# $job = new \App\Jobs\TestSession(1, false);Bus::dispatch($job);
# $job = new \App\Jobs\TestSession(2, false);Bus::dispatch($job);
# @see https://github.com/laravel/framework/issues/20908
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class TestSession implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
const SESSION_KEY = 'number';
public $force_reload = false;
public $number;
/**
* What queue should this job use.
*
* @var string
*/
public $queue_name = "mail";
/**
* How many tries before this job fails?
*
* @var int
*/
public $tries = 3;
/**
* When should we consider this job failed? (seconds)
*
* @var int
*/
public $timeout = 60;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($number, $force_reload)
{
$this->number = $number;
$this->force_reload = $force_reload;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
\Log::info("Using {$this->number} I should get {$this->fetch($this->number)}");
$details = $this->fetchUserDetails($this->number);
\Log::info("Got {$details}");
}
private function fetchUserDetails($number)
{
if (empty($details = session()->get(self::SESSION_KEY)) || $this->force_reload) {
$details = $this->fetch($number);
session([self::SESSION_KEY => $details]);
} else {
\Log::info('Bypassing session, already set');
}
return $details;
}
private function fetch($number)
{
$map = [
1 => 'Streatham',
2 => 'All',
];
return $map[$number];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment