If you’re a PHP developer looking for a guide that teaches you the concepts behind implementing segregated interfaces and how to utilize them, then you have come to the right place. This series of articles will show you how to define fine-grained contracts for your classes, so that they can perform only the tasks they’re responsible for.
In the last installment of this series, I went through the development of a basic registry system, which was capable of using different registry classes to store, retrieve and even dump data. The most engaging aspect of this sample system was that the swappable registry classes implemented a couple of segregated interfaces in order to execute the aforementioned operations.
As with other elements of object-oriented programming, it’s possible to use segregated interfaces in a great variety of scenarios and conditions and, therefore, enjoy the benefits that they provide right out of the box.
If you missed the first two parts in this series, or need a quick refresher, you can find them at:
Making the initial move: defining a segregated interface
As I stated in the introduction, my goal in this article is to create an extendable caching system based on the contract defined by a segregated interface. To achieve this, the first step we need to take is to create the interface in question.
The following code creates an interface we will call “CacheableInterface”, which sets a contract that outlines the behavior of an abstract cache back-end. Check it out:
(CacheableInterface.php)
<?php
interface CacheableInterface { public function set($key, $data);
public function get($key);
public function delete($key);
public function exists($key); }
As shown above, the “CacheableInterface” interface declares a set of methods that permit you to create several different cache back-ends with minor effort. You should pay particular attention to the contract established by the pertinent methods: effectively, any further implementer will have only the functionality required for setting, fetching, checking and even removing elements from the underlying cache mechanism.
This example clearly shows how the use of a segregated interface may help in the creation of classes that have a well-defined range of responsibilities.
Now that our granular contract exists, the next step is to create a couple of them, which will allow you to cache data using both the APC PHP extension and the file system as well.