PHP Classes

Car - Class analogy

Recommend this page to a friend!

      PHP Dependency Injection Container  >  PHP Dependency Injection Container package blog  >  Improving Your PHP Pr...  >  All threads  >  Car - Class analogy  >  (Un) Subscribe thread alerts  
Subject:Car - Class analogy
Summary:its all about controlling how objects interacts with one another
Messages:1
Author:Samuel Adeshina
Date:2015-11-03 19:07:45
 

  1. Car - Class analogy   Reply   Report abuse  
Picture of Samuel Adeshina Samuel Adeshina - 2015-11-03 19:07:45
Think of an instance where you want to create a database query class (or service)
You need to provide a connection to your database, this is what the query class uses to "make the necessary connections to the DB and executes queries successfully". Usually, a separate class handles the connection.

You can pass your connection class into your query class as a dependency, in other words, you inject the connection class (the dependency, a service or factory needed by other objects or services) into your query class which is the object that's dependent on another object.

<?php
class connection
{
public function conn()
{
//perform connections to the database
}
}

class query
{
public function __construct(connection $connObj)
{
$connObj->conn()
//we've just established a connection to the DB
}
}

?>

The above code snippet is a better illustration of the DI concept. Think of the connection class as the "automobile object" and the query class as the "car object" for a "car class" analogy.

Watch out for the next part of the article that talks about how to properly inject objects, more on the single responsibility principle and how to build a DI container like Pimple.