Is this a right way of using the command bus with a database transaction?

Posted 3 years ago by selmonal

I've been using extended version of Laravel Dispatcher class. That overrides dispatchNow method it provides a database transasction if the command implements ShouldUseDatabaseTransaction.

Please see the code below.

Command should implement this interface:

interface ShouldUseDatabaseTransaction
{
}

Here is the Dispatcher class.

class Dispatcher extends LaravelDispatcher
{
    /**
     * @param mixed $command
     * @param Closure|null $afterResolving
     * @return mixed
     */
    public function dispatchNow($command, Closure $afterResolving = null)
    {
        if(! $this->commandShouldUseDatabaseTransaction($command)) {
            return parent::dispatchNow($command, $afterResolving);
        }

        return DB::transaction(function() use($command, $afterResolving) {
            return parent::dispatchNow($command, $afterResolving);
        });
    }

    /**
     * @param $command
     * @return bool
     */
    private function commandShouldUseDatabaseTransaction($command)
    {
        return ($command instanceof ShouldUseDatabaseTransaction);
    }
}

It works fine for me but Is this right way of doing it? If it is not what is the best and short way? please help me!

Please sign in or create an account to participate in this conversation.