When to use the command bus?

Posted 3 years ago by JackEdwards

So, I've recently learned about commands. They are awesome.

What I'm wondering though is when should you and when should you not use commands?

For example, I have projects in my website that users can join and leave. Originally I had a bunch of code in the 'join' function of my controller, but I decided to move that into a 'JoinProject' command like so:

public function handle()
{
    if (!$this->user->isLeader($this->project)) {
            if (!$this->project->users->contains($this->user->id)) {
                    $this->project->users()->save($this->user);
                }
        }
}

This has cleaned up my controller a lot already because now my join function consists only of this:

public function join(Project $project)
{
    $this->dispatch(new JoinProject(Auth::user(), $project));

    return Redirect::back();
}

In this situation I was only replacing about 5 lines of code - is it good practice to create commands for simpler situations?

For example, I have some code in the destroy() function of my controller to delete a project:

if (Auth::user()->isLeader($project)) {
    $project->delete();
}

That's only 3 lines of code, but would it be a good idea to encapsulate it inside a Command in case in the future I change the code to perform more tasks when a project is deleted?

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

Reply to

Use Markdown with GitHub-flavored code blocks.