Object-Oriented PHP: Interfaces

In our previous lesson we've talking about Inheritance. In this lesson we will be discussing about interfaces. Think of interface as a contract that a class should follow once it implements it.
Let's take a look on how to create and implements an interface. Let's stick in our previous example of a shape.
<?php
interface Shape
{
public function getArea();
}
class Circle implements Shape
{
protected $radius = 5;
public function getArea()
{
return M_PI * pow($this->radius, 2);
}
}
$circle = new Circle;
echo $circle->getArea();
As you can see, when creating an interface we have to use the keyword interface
, and implements
when we are going to use it.
When to use an interface?
An interface can be use when you are in a situation where a certain functionality can be implemented in a lot of different ways. Like for example, let's say we have to add a caching functionality in our application. So, at first we decided to simply use a file for caching.<?php
class FileCache
{
public function forever()
{
return 'Caching using file';
}
}
class UserController
{
protected $cache;
public function __construct(FileCache $cache)
{
$this->cache = $cache;
}
public function profile()
{
return $this->cache->forever();
}
}
$user = new UserController(new FileCache);
echo $user->profile();
As you can see, we are just using a concrete class here. The problem with this is when we decide to use another type of caching in the future like database for example, and we use this FileCache
class everywhere in our application. Although you can use find an replace feature of your editor, but for me it's not the most practical way to solve this kind of problem.Instead, we can use an interface for this. Let me show you how.
<?php
interface Cacheable
{
public function forever();
}
class FileCache implements Cacheable
{
public function forever()
{
return 'Caching using file';
}
}
class DatabaseCache implements Cacheable
{
public function forever()
{
return 'Caching using database';
}
}
class UserController
{
protected $cache;
public function __construct(Cacheable $cache)
{
$this->cache = $cache;
}
public function profile()
{
return $this->cache->forever();
}
}
$user = new UserController(new DatabaseCache);
echo $user->profile();
Now, our UserController
will not care anymore on what type of caching are we going to pass, as long as that class adheres the Cacheable
interface.That's all for this lesson. If you have any questions please don't hesitate to write it down in the comment below. See you in the next lesson.
Previous: Inheritance
Post a Comment