The main advantage I see of this in PHP is the issue of providing programmer flexibility in the case of using a library where it implements its own feature.
In this case, the programmer could simply use his own class as long as he implements the interface required to perform such an operation.
An example: These days, I was having a problem with the Facebook library because I use Laravel
, and Laravel
does not use the native PHP session. Facebook uses the native PHP session. The result is that I was having a problem.
The Facebook
class implements an interface called PersistentDataInterface
. This interface had the set
and get
methods required to determine how data would be saved in the session.
As the typing of the data is done through PersistentDataInterface
, I implemented it, causing the methods to save and retrieve data from the session of Laravel
.
So, everything worked correctly.
Then look at 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
of class Library
requires typing to be the implementation of interface
, and not classe
itself. So, this gives me more flexibility so that I create another class with the interface methods, but they persist the data differently!
I think using the interface is good practice when you want to offer more ways for your library to interact with other classes. Because you "force" the third class to use the methods through the interface, you can call a method of the object passed by parameter without "being afraid" that the method does not exist and have to be doing thousands of ifs with% / p>
THE FUTURE
In method_exists
it will be wonderful to combine the interfaces feature with PHP7
, as this gives you even more flexibility. See for example, in the case above, 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);