Dependancy injection is providing your application what it needs to function, which is any data. Most application are modular, they behave like separte components or entities. But all need to take in something to function.
So, that thing they need is their dependancy.
This can be passed via a class contructor, which is ideal as when the an object is initialized the contructor is the first function that gets called, so anything your app needs to work can be passed via the constructor. But sometimes you can pass the data directly to the method as an argument to your function/method Ex:
# Generic Input validator
class InputValidator{
function isEmailValid($email){}
}
# Our main application
class UserRegistration(){
function Register($inputValidator){
$isEmailValid = $inputValidator->isEmailValid('foo@bar.com');
}
}
# Instanciating the class and providing the dependancy
(new UserRegistration)->Register(new InputValidator());
In the above example, the UserRegistration->Register()
depends on the class InputValidator()
to register a user, we could have provided the email validator directly in the UserRegistration
class, but we choose to pass it as a dependancy instead make our application as a whole S.O.L.I.D compliant.
So, in short we are injecting the dependancy there. That is dependancy injection.
Type Hinting is, much simpler to understand.
Basically, if we extend our previous example and if you check Register(new InputValidator());
you can see that we passed it the
class it needs to function, but someone mistakenly could also pass another class or even a string such as: Register('something');
which would break the application, since
Method Register
does not need a string. To prevent this, we can typehint it, in other words tell the Register
function only to accept
certain type of data : array, object, int ... or we can even explicitly inform it to take a class name by providing it before as
$InputValidator = new InputValidator();
Register(InputValidator $InputValidator);
as for composition, this is a better read that I can provide What is composition as it relates to object oriented design?