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