Laravel introduction to Service Container — Part 1

We have to talk about the Service Container because it’s a powerful tool for managing class dependencies and performing dependency injection.

Dependency Injection: The classes we depend on are “injected ”via the constructor or other setter methods in our class

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use App\Models\User;
class UserController extends Controller
{

protected UserRepository $users;

public function __construct(UserRepository $users)
{
$this->users = $users;
}

public function get(int $id)
{
$user = $this->users->find($id);
}
}

In this example we have to retrieve some data from a database, so we need a repository ( where we most likely have DB queries to get our data ), and because the repository is injected it’s really easy to swap it out with another implementation and mock it for unit tests!

The Zero Configuration Resolution

It is a really simple concept yet it may be hard to grasp.

It states that if a class only depends on concrete classes, the container does not need to be instructed on how to resolve that class.

This means that those classes will be automatically resolved.

Thankfully, most of the things we do will receive their dependencies via the container. This will resolve all our dispatchers, listeners, middleware, etc.

Dependency Injection inside Laravel Jobs

Dependency injection should be made inside the handle method, not in the constructor as I have stated above.

<?php

namespace App\Jobs;

use App\Services\PinService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessPodcast implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


public function __construct()
{

}


public function handle(PinService $pinService)
{

}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store