Understanding IoC, Simple Factory, and Dependency Injection in PHP

This article explains the Inversion of Control (IoC) pattern, demonstrates a simple factory for creating traffic‑tool objects, and shows how to apply Dependency Injection (DI) in PHP to decouple a Student class from concrete transportation implementations, culminating in a lightweight IoC container example.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Understanding IoC, Simple Factory, and Dependency Injection in PHP

The article introduces the IoC (Inversion of Control) pattern as a way to solve component dependencies, using a school‑going scenario where a Student needs a Go_To_School implementation.

First, a simple interface interface Go_To_School { public function go(); } is defined, followed by concrete classes Foot, Car, and Bicycle that implement this interface, each printing a different message.

A Student class is then shown with a private $trafficTool property. The constructor manually creates a Foot instance, illustrating tight coupling and the need for a better solution.

To reduce coupling, a simple factory

class TrafficToolFactory { public function createTrafficTool($name) { switch($name) { case 'Foot': return new Foot(); case 'Car': return new Car(); case 'Bicycle': return new Bicycle(); default: exit('set trafficTool error!'); } } }

is introduced, and the Student constructor receives a traffic‑tool instance via dependency injection.

Finally, a minimal IoC container is presented. The container stores bindings with $ioc->bind('Go_To_School', 'Car'); and $ioc->bind('student', 'Student');, and resolves them using $student = $ioc->make('student'); $student->go_to_school();. The container can also bind callbacks, e.g.,

$ioc->bind('Go_To_School', function() { return new Car(); });

, allowing flexible creation of dependencies.

Through these examples, the article demonstrates how moving object creation out of classes and into factories or an IoC container eliminates hard‑coded dependencies, making the codebase easier to maintain and extend.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Design PatternsIoCPHPdependency-injection
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.