Laravel - Jobs - Sessions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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