Currently I am investigating several ways of handling dependencies in PHP – stuff like Dependency Injection, the Service Locator pattern and the different implementations of these.
One common thing that is also the point of this question is the use of interfaces. Let's say I wrote a class the stores & retrieves some data from somewhere (doesn't matter for that example):
class DataStuff
{
public function store($data)
{
// Do stuff
}
public function retrieve($id)
{
// Do other stuff
}
}
When I want to make this class available for other developers to use or for use in other projects, I've read it's recommended to use an interface, which is then implemented by my actual class:
interface DataStuffInterface
{
public function store($data);
public function retrieve($id);
}
class DaDataStuff implements DataStuffInterface
{
// Same as above
}
Why is it recommended to use an interface like this?
I know that is has something to do with type hints/Dependency Injection, because stuff like this can be done with it, but I don't really get the point of it:
public function __construct(DataStuffInterface $dataStuffInterface) {
// Do something here
}
Where would I place code like this – does is have something to do with factories? Why shouldn't I just do it like this:
public function __construct(DataStuff $dataStuff) {
// Do something here
}