paint-brush
Introduction to Interfaces and Polymorphismby@anastasionico
845 reads
845 reads

Introduction to Interfaces and Polymorphism

by anastasionicoOctober 16th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Discover the secrets of polymorphism, one pillar of Object-Oriented Programming

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Introduction to Interfaces and Polymorphism
anastasionico HackerNoon profile picture

Discover the secrets of polymorphism, one pillar of Object-Oriented Programming

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

    function

    {

    }

    function

    {

    }

    function

    {

    }

    function

    {

    }

}

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

    function

    {

    }

    function

    {

    }

}

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

Let’s have a look at an example:

$obj

$obj->data = "My private data";

$ser

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.

Countable

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

Seriously?

interface

    function

    {

    }

}


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

    function

    {

    }

    // Methods inherited from Iterator

    function

    {

    }

    function

    {

    }

    function

    {

    }

    function

    {

    }

    function

    { 

    }

}

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

    function

    {

    }

    function

    {

    }

    // Methods inherited from Iterator

    function

    {

    }

    function

    {

    }

    function

    {

    }

    function

    {

    }

    function

    {

    }

}

RecursiveIterator on php.net

SeekableIterator

This method allows you to investigate an Iterator,

Interface SeekableIterator extends

    function

    {

    }

    // Methods inherited from Iterator

    function

    {

    }

    function

    {

    }

    function

    {

    }

    function

    {

    }

    function

    {

    }

}

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

    {

    }

}

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

    {

    }

}

class

{

    ...

    function

    {

    return

    }

}

class

{

    ...

    function

    {

    return

    }

}

function

    $interestRate

    return

}

$school

$office

echo

echo

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 anyway soon the following parts will be published.

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!