What is a Service Container / IoC Container in PHP ?

profile picture

What is a Service Container / IoC Container in PHP ?

"IoC" stands for Inversion of Control and I already talked about it in my PHP Course : What Is Dependency Injection

As for the "Container", also called Dependency Injection Container, Service Container, or DI Container, it is a tool to help injecting dependencies.

Many PHP Framework come with their own Container, but they more or less all work the same.

Basically a DI Container is like a box in where you put objects that you want to use later. Each objects are assigned to a key, and you can retreive the object by using the right key.

You can also view this as a giant Object or a Store. You assign properties to that objects like you would do to any PHP Class.

But of course, PHP frameworks supercharge their DI Container with interesting features.

Imagine you have a Hashing class that you use to hash and/or crypt user passwords, we will call it simply Hash::class

During the build time of your application, let's put that class inside our container.

$container = [];
$container['hash'] = Hash::class;

// Now it's up to you to make that $container variable accessible anywhere in your application

Let's make a basic controller:

class LoginController extends Controller
{
    public __construct($container)
	{
		$this->container = $container;
	}
	
    public function login($email, $password)
	{
	    $hashedPassword = (new $this->container['hash'])->hash($password);
	}
}

This is just an example piece of code for you to understand this very simple concept of putting any class in an application container box, accessible from anywhere in your code (as long as you use your dependency injection correctly).

And basically that's it !! I suggest to read the Symfony documentation regarding their "Service Container" or the Laravel one as they explain really well what it's for.

php
ioc
di
container
service

about me

profile picture

I consider myself as an IT Business Artisan. Or Consultant CTO. I'm a self-taught Web Developper, coach and teacher. My main work is helping and guiding digital startups.

more about me

follow me

newsletter

A weekly email with the latests articles

support my work

Start trading on binance
  • BTC

    BTC

    18SY81ejLGFuJ9KMWQu5zPrDGuR5rDiauM

  • ETH

    ETH

    0x519e0eaa9bc83018bb306880548b79fc0794cd08

  • Monero

    XMR

    895bSneY4eoZjsr2hN2CAALkUrMExHEV5Pbg8TJb6ejnMLN7js1gLAXQySqbSbfzjWHQpQhQpvFtojbkdZQZmM9qCFz7BXU

recent posts

QBUS - MQTT Quick Tutorial

1
11 months ago

DDOS By Web Crawlers

1
1 year ago

Something Given

1
1 year ago

2024 © My Dynamic Production SRL All rights Reserved.