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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
