Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

StackOverflow

StackOverflow Logo StackOverflow Logo

StackOverflow Navigation

Search
Ask A Question

Mobile menu

Close
Ask A Question
  • Home
  • Add group
  • Feed
  • User Profile
  • Communities
  • Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
Home/ Questions/Q 502
Next

StackOverflow Latest Questions

Saralyn
  • 0
  • 0
SaralynBegginer
Asked: January 31, 20252025-01-31T10:21:05+00:00 2025-01-31T10:21:05+00:00In: PHP

php – How to Implement Queue with Custom Database in Multitenant Architecture?

  • 0
  • 0
php – How to Implement Queue with Custom Database in Multitenant Architecture?

I just thought of a quick and dirty way that you can use to achieve this. I would create an abstract Base class like so;

abstract class BaseTenancyJob implements ShouldQueue
{
  use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

  
  public function __construct(public ?int $tenancyId = null)
  {
     $this->initialize();
  }


  public function initialize(): void
  {
     //this could have been set prior at the initial instantiation of the app
     //when the app still had context because I would assume if a job gets fired
     //it would mostly be when there was context but in case there was no context
     //the tenancyId would then be passed in like the example you gave.
    $this->tenancyId = $this->tenancyId ?? config('app.tenancy_id');
  }


  public function middleware(): array
  {
      return [
        new PreserveTenancyConfig($this->tenancyId),
      ];
  }
}

Then I’ll create a middleware that runs before the job is processed. This middleware is what is passed as part of the middleware in the BaseJob class. What it will do is to set the tenancy config. In cases like this, I feel database is just one of many things that could be needed, so that method should take care of everything including database change.

class PreserveTenancyConfig
{

 public function __construct(public ?int $tenancyId = null) {}

/**
 * Handle the job and preserve the config context.
 *
 * @param  mixed  $job
 * @param  callable  $next
 * @return void
 */
public function handle(mixed $job, callable $next): void
{
    if (! is_null($this->tenancyId)) {
        //do some query with the Id to resolve tenancy
        $tenancy = Tenancy::find($this->tenancyId);
        
        //TenancyService facade
        //I've put the suggestion of a facade here as you may need
        //to do a lot like get config, set config in different places
        //you don't want to bother about instantiating the service class
        //from time to time.
        \App\Tenancy\Tenancy::setTenancyToConfig($tenancy);
    }
    $next($job);
}

The setTenancyToConfig() method could look like this;

/**
 * @param  Tenancy $tenancy
 * @return void
 */
public function setTenancyToConfig(Tenancy $tenancy): void
{
    config()->set('app.tenancy_id', $tenancy->id);
    config()->set('app.name', $tenancy->name);
    config()->set('database.connections.'.$tenancy->database, $tenancy->database_connection);
    config()->set('database.default', $tenancy->database);
}

Now the actual job could look like so;

class TestJob extends BaseTenancyJob
{
  /**
   * Create a new job instance.
   *
   * @param  string  $someValue
   * @param  int|null  $tenancyId
   */
   public function __construct(public string $someValue, public ?int $tenancyId = null)
   {
      parent::__construct($this->tenancyId);
   }

  /**
   * Execute the job.
   *
   * @return void
   */
  public function handle(): void
  {
    //if everything works out this should dump the tenancyId you have set
    //it would also mean everything you have set will now take precedence
    dump(config('app.tenancy_id'));
    dump($this->someValue);
    dump(User::count()); // A way to track data change as DB would have changed.
  }
}

I don’t particularly like this solution but it should solve your problem.

Modifying your example the way it’s currently without any big modification based on the suggestion I’ve here would look like this;

class YourJob extends BaseTenantJob
{
  /**
   * Create a new job instance.
   */
   public function __construct(private array $tenantDetails)
   {
      parent::__construct($this->tenantDetails);
   }

  /**
   * Execute the job.
   *
   * @return void
   */
  public function handle(): void
  {
     //Do whatever in your job
  }
}


abstract class BaseTenantJob implements ShouldQueue
{
  use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

  
  public function __construct(private array $tenantDetails)
  {
  }


  public function middleware(): array
  {
      return [
        new PreserveTenantConfig($this->tenantDetails),
      ];
  }
}

class PreserveTenantConfig
{

 public function __construct(private array $tenantDetails) {}

/**
 * Handle the job and preserve the config context.
 *
 * @param  mixed  $job
 * @param  callable  $next
 * @return void
 */
public function handle(mixed $job, callable $next): void
{
        config()->set('database.connections.'.$tenantDetails['database'], $tenantDetails);
config()->set('database.default', $tenantDetails['database']);

    $next($job);
}

NB: I’ve made some assumptions with tenantDetails, adjust accordingly and this will definitely work.

0
  • 0 0 Answers
  • 94 Views
  • 0 Followers
  • 0
Answer
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question
  • Popular
  • Answers
  • W3spoint99

    What is Physics? Definition, History, Importance, Scope (Class 11)

    • 1 Answer
  • W3spoint99

    The Living World – Introduction, Classification, Characteristics, FAQs (Class 11 ...

    • 1 Answer
  • W3spoint99

    Explain - Biological Classification (Class 11 - Biology)

    • 1 Answer
  • Saralyn
    Saralyn added an answer When Humans look at their childhood pictures, the first thing… January 17, 2025 at 3:25 pm
  • Saralyn
    Saralyn added an answer Previously, length was measured using units such as the length… January 17, 2025 at 3:25 pm
  • Saralyn
    Saralyn added an answer Measurement forms the fundamental principle to various other branches of… January 17, 2025 at 3:25 pm

Related Questions

  • Reading fancy apostrophe PHP [duplicate]

    • 0 Answers
  • Unable to send mail via PHPMailer [SMTP->Error: Password not accepted ...

    • 0 Answers
  • Concerns when migrating from PHP 5.6 to 8.4 [closed]

    • 0 Answers
  • Laravel Auth::attempt() error: "Unknown column 'password'" when using a custom ...

    • 0 Answers
  • Core PHP cURL - header origin pass null value

    • 0 Answers

Trending Tags

biology class 11 forces how physics relates to other sciences interdisciplinary science learn mathematics math sets tutorial null sets physics physics and astronomy physics and biology physics and chemistry physics applications science science connections science education sets in mathematics set theory basics types of sets types of sets explained

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

  • About US
  • Privacy Policy
  • Questions
  • Recent Questions
  • Web Stories

© 2025 WikiQuora.Com. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.