Wednesday, 9 November 2016

PHP Interfaces

When building multiple PHP classes that are interchangeable - for instance two user classes where one reads from a MySql database and one from a JSON file - it is crucial that these classes do not diverge in functionality; If you add a 'getUserInfo' method to the one, you have to add it to the other, chances are you are using a factory to instantiate your objects and would thus expect to be able to use them in exactly the same manner. An interface solves this problem.
An interface provides a set of rules that determine the shape of the class that implements this interface. In the above example the interface will enforce the existence of a 'getUserInfo' method in both the UserMySql and UserJSON classes.

Building an interface

Let's build an interface for the example above. A user class that fetches it's data from a MySql database, and a user class reads from a JSON file. These must both contain public 'create', 'read', 'update' and 'delete' methods.
interface.account.php
<?php
interface Account {
  public function create(string $name, string $email);
  public function delete();
  public function read(int $id);
  public function update(string $name, string $email);
}
?>
class.user.json.php
<?php
class UserJSON implements Account {
  public $id;
  public $name;
  public $email;
  public function create(string $name, string $email) {
    // insert into JSON file
  }
  public function delete() {
    // delete user with {$this->id}
  }
  public function read(int $id) {
    // read user from {$id}.json
  }
  public function update(string $name, string $email) {
    // update user with {$this->id}
  }
  public function doesSomethingElse () {
    // do something else
  }
  private function doesSomethingDifferent () {
    // do something different (and private)
  }
}
?>
class.user.mysql.php
<?php
class UserJSON implements Account {
  public $id;
  public $name;
  public $email;
  public function create(string $name, string $email) {
    // insert into JSON file
  }
  public function delete() {
    // delete user with {$this->id}
  }
  public function read(int $id) {
    // read user from {$id}.json
  }
  public function update(string $name, string $email) {
    // update user with {$this->id}
  }
}
?>
The interface and two classes above will work together well and the interface will keep the classes aligned properly. If either of these classes do no conform to the shape provided in the interface PHP will throw an error thus indicating that the class does not conform.

No comments:

Post a Comment