The main advantage I see of this in PHP is the question of providing flexibility to the programmer in the case of using a library where he implements his own resource.
In this case, the programmer could simply use his own class, provided that he implements the interface required to perform such an operation.
An example: These days, I was having trouble with the Facebook library, because I use the Laravel
, and the Laravel
does not use the native PHP session. Facebook uses the native PHP session. The result is that it was having trouble.
The class of Facebook
implements an interface called PersistentDataInterface
. This interface had the methods set
and get
, needed to determine how the data would be saved in the session.
How data typing is done through PersistentDataInterface
, I implemented it, causing the methods to save and obtain data directly from the Laravel
.
So everything worked out correctly.
So here’s an example:
interface PersistentData {
public function set($key, $value);
public function get($key);
}
class Library{
public function __construct(PersistentData $persist)
{
$this->persist = $persist;
}
}
class ClasseQueNaoAtendeMeuSistema implements PersistentData
{
public function set($key, $value) { ... }
public function get($key);
}
In this case, the construtor
class Library
requires typing to be the implementation of interface
, and not of classe
in itself. Therefore, this gives greater flexibility for me to create another class with the interface methods, but that make the data persistence differently!
I believe that using the interface is a good practice when you want to offer more ways your library can interact with other classes. As you "force" the third class to use the methods through the interface, you can call an object method passed by parameter without "being afraid" that the method does not exist and have to keep making thousands of ifs with method_exists
.
THE FUTURE
In the PHP7
it will be wonderful to join the resource of the interfaces with the classes anônimas
, as this gives even more flexibility. See for example, in the above case, what could be done.
$tempPersist = new class(Database::connection()) implements PersistentData
{
public function __construct(Database $database)
{
$this->database = $database;
}
public function set($key, $value)
{
$this->database->table('session')->save([$key=>$value]);
}
public function get($key)
{
return $this->database->table('session')->get($key);
}
}
$lib = new Library($tempPersist);
Ivan, the main advantage I see is that the guy doesn’t have to stare at the code of the class that does something, but simply knows the interface that the class implements
– Wallace Maxters
So, you see this as an advantage, a colleague of mine from the job said that I should always use it in my systems, but then I get in a glaring doubt, if we start creating a more bureaucratic code, it doesn’t get a very plastered thing?
– Ivan Ferrer