Interfaces and Polymorphism in PHP

Coding (Php 7.x)


Discover the secrets of polymorphism, one pillar of Object-Oriented Programming
 
/img/blog/interfaces-and-polymorphism-in-oop.jpg

Follow the series ...

 

This blog post is the third part of  "The complete guide to Object-Oriented Programming: Go from procedural programming to OOP expert in PHP"

 

If you did not read the other parts yet

You can check the other blog posts following the links below 
Introduction to Object-Oriented Programming
Inheritance and Interfaces in PHP
More Interfaces and Polymorphism
Visibility and Static keyword
Constructor and Magic methods and  
Abstract Classes and Extra bits 

 

Introduction to Interfaces and Polymorphism

 

As Web Developers you need to know that times and times again you are going to rewrite, update or delete some features on codes that you have deployed ages before.

 

Once moved from the procedural paradigm and starting to learn the basics of Object-Oriented programming you will find out that the code has not only to be clean and scalable but it has to be manageable.


and this worth for PHP as well as other programming languages.


The scripts have to be so easy to work with that you won't want to change job if your technical director asks you to refactor or add new characteristics.

 

Some of the techniques used to write code that is reliable now as much as in the long-term are the use of interfaces and a clear understanding of polymorphism.

 

If you missed it, Click here to understand what an interface is and to check the first build-in interfaces of the PHP language out.

 

Otherwise, below you will find the second part of the list explaining PHP interfaces (you will not use them on daily basis but you must know that they exist and make them part of your swiss knife when needed).

and a brief and clear explanation of the concept of polymorphism.


Let get started.

 

 

ArrayAccess

This interface let objects being accessed as arrays.

 

The main benefit of this behaviour is structural

Object properties are usually well defined and of different types.

If you implement ArrayAccess you tell to the script "My objects can also behave like arrays".

interface ArrayAccess {
    function offsetExists ()
    {
    }
    function offsetGet ()
    {
    }
    function offsetSet ()
    {
    }
    function offsetUnset ()
    {
    }
}

ArrayAcces on php.net


Serializable

“To serialize” verb,

Arrange (something) in a series. (Oxford Dictionaries).

 

Sometime you may need a collection of data to be combined and ordered in a certain way.

 

The Serializable interface allows you to transform your data in a formatted string which is much easier to be transported and imported elsewhere.

interface Serializable {
    function serialize ()
    {
    }
    function unserialize ()
    {
    }
}

Implement this interface on an object will mutate the format of the data,

Let’s have a look at an example:

$obj = new obj;
$obj->data = "My private data";
$ser = serialize($obj);
var_dump($ser);
// the var_dump above will print: string(38) "C:3:"obj":23:{s:15:"My private data";}"

In the next episode of this article, I will explain what magic methods are but for now, just keep in mind that:

If a class implement this interface it will no longer support the __sleep() and the  __wakeup() methods.

Serializable on php.net

 

 

Countable

The reason to implement it in a class is to count.

Seriously?

interface Countable {
    function count ()
    {
    }
}

Within this function, you can count the number of objects,
count the elements of an array or even just return a number.

Countable on php.net

 

OuterIterator

We have already touched Iterators previously,

PHP consent you to loop through several types of data: arrays, databases, object, directory structures, etc.

Sometimes you what to iterate over another iterator that is iterating over something else.

PHP has got you covered and it does it by using the OuterIterator interface.

It has only one method getInnerIterator() and extend the Iterator interface

Interface OuterIterator extends Iterator {
    function getInnerIterator ()
    {
    }
    // Methods inherited from Iterator
    function Iterator::current ()
    {
    }
    function Iterator::key ()
    {
    }
    function Iterator::next ()
    {
    }
    function Iterator::rewind ()
    {
    }
    function Iterator::valid ()
    {
    }
}

 

 

The OuterIterator needs to extend Iterator which means you must implement all the methods that follow.

OuterIterator on php.net

 

RecursiveIterator

This interface is very similar to the previous one.

In fact,

 

Class that implements RecursiveIterator simply iterates over iterators recursively

 

It has two own methods and extends the Iterator interface as well.

Interface RecursiveIterator extends Iterator {
    function getChildren ()
    {
    }
    function hasChildren ()
    {
    }
    // Methods inherited from Iterator
    function Iterator::current ()
    {
    }
    function Iterator::key ()
    {
    }
    function Iterator::next ()
    {
    }
    function Iterator::rewind ()
    {
    }
    function Iterator::valid ()
    {
    }
}

RecursiveIterator on php.net

 

SeekableIterator

This method allows you to investigate an Iterator,

Interface SeekableIterator extends Iterator {
    function seek ()
    {
    }
    // Methods inherited from Iterator
    function Iterator::current ()
    {
    }
    function Iterator::key ()
    {
    }
    function Iterator::next ()
    {
    }
    function Iterator::rewind ()
    {
    }
    function Iterator::valid ()
    {
    }
}

 

The method seek allow to seek to a position of the Iterator

SeekableIterator on php.net

 

SplObserver and SplSubject

Both SplObserver and SplSubject are used alongside each other to implement the Observer Design Pattern

Here is a video tutorial form Christopher Okhravi’s youtube channel

Interface SplObserver {
    function update ()
    {
    }
}

 

SplObserver on php.net 

SplSubject on php.net

 

 

 

Polymorphism

 

Early on in this article, you discovered that in Object-Oriented Programming one of the fundamentals is the inheritance,

 

Here is another of the pillar of OOP

 

To simplify this very harsh word I can use the following sentence:

 

If classes have different functionality but share a common interface here is where you see polymorphism.

 

In a practical example polymorphism is writing the same code and giving it the same name but allowing it to take a slightly different type of argument variable or input and then output a slightly different result depending on these parameters.

Interface Building
{
    function evaluate ()
    {
    }
}

class School implements Building
{
    ...
    function evaluate ()
    {
        return $studentCount + $teachersCount;
    }
}

class Office implements Building
{
    ...
    function evaluate ()
    {
        return $computersCount
    }
}

function getPrice( Building $building) {
    $interestRate = 0.2;
    return $building->evaluate() * $interestRate;
}

$school = new School();
$office = new Office()
echo getPrice($school);
echo getPrice($office);

 

The example above illustrates in a simple way (at least I hope so) of how polymorphism works.

 

We still have our beloved buildings, and we need to get their price.

 

The complication stays in the fact that even though we need to calculate the same thing (in our case the price) the evaluation to find the price is calculated in two different ways.

 

A school gets this valuation by the number of students plus the number of teachers that work in it.

 

The office instead gets its evaluation from the number of computers within the building.

 

By creating the building interface and declare it in the getPrice() function we can require a different type of building such as schools, office, and others without compromising security.

 

The nice thing about polymorphism is that the code will work with the multiple classes and it does not need to know which class it is being used because they're all used the same way.

 

Polymorphism is mainly used to make applications modular. 


Instead of using conditional statements that create different actions, you create interchangeable objects that you select based on the needs of the moment.

 

the principle of polymorphism is keeping your components separate and it does it very well.


for this reason, you will find it in many design patterns,

but this is a story for another time...

 

 

Conclusion of the third part

The full version of "The complete guide to Object-Oriented Programming" in an all-in-one edition is available in a Kindle format on Amazon

 

Here you have it, 

 

as I said there are plenty of built-in interfaces in PHP.

 

Even if you rarely will use them it is good to know that they exist and when there will be the need of its use you will be able to use them.

 

Same thing for polymorphism,
It is a concept quite difficult to grasp at the beginning but once you understood the reason why it helps improve the quality of your code,  you are going to want to master its implementations everywhere you see a leak in the program.

 

Now it is your turn:

Let me know it the comment below which interface it's more useful for your and how do you want to insert it in your code?

 

 
 
If you like this content and you are hungry for some more join the Facebook's community in which we share info and news just like this one!

Other posts that might interest you

Coding (Php 7.x) Oct 8, 2018

Inheritance and Interfaces in PHP

Learn more See details
Coding (Php 7.x) Oct 22, 2018

Visibility and Static keyword in PHP

Improve your Skills See details
Coding (Php 7.x) Oct 29, 2018

Magic Methods in OOP: The Definitive Guide (PHP)

Other magic Here See details
Get my free books' review to improve your skill now!
I'll do myself