• Stars
    star
    126
  • Rank 275,876 (Top 6 %)
  • Language
    PHP
  • Created over 6 years ago
  • Updated almost 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Interface and abstract class - simple and easy explanation

Welcome to OOP

Interface

We know that an interface is defined by the interface keyword and all methods are abstract. All methods declared in an interface must be public; this is simply the nature of an interface. Here is the example :

<?php
interface Logger
{
    public function execute();
}

In an interface the method body is not defined, just the name and the parameters. If we do not use an interface what problems will happen? Why we should use interface? Herein you will get these answers. Please see the code in below:

<?php
class LogToDatabase 
{
    public function execute($message)
    {
        var_dump('log the message to a database :'.$message);
    }
}

class LogToFile 
{
    public function execute($message)
    {
        var_dump('log the message to a file :'.$message);
    }
}

class UsersController 
{ 
    protected $logger;
    
    public function __construct(LogToFile $logger)
    {
        $this->logger = $logger;
    }
    
    public function show()
    { 
        $user = 'nahid';
        $this->logger->execute($user);
    }
}

$controller = new UsersController(new LogToFile);
$controller->show();

In the above example I do not use interface. I write to the log using the LogToFile class. But now if I want to write a log using LogToDatabase I have to change hard coded class reference in the above code on line number 23. That line code in below :

public function __construct(LogToFile $logger)

This code will be

public function __construct(LogToDatabase $logger)

In a large project, if I have multiple classes and a need to change, then I have to change all the classes manually. But If we use an interface this problem is solved; and we will not need to change code manually.

Now see the following code and try to realize what happened if I use interface:

<?php
interface Logger 
{
    public function execute($message);
}

class LogToDatabase implements Logger 
{
    public function execute($message){
        var_dump('log the message to a database :'.$message);
    }
}

class LogToFile implements Logger 
{
    public function execute($message) 
    {
        var_dump('log the message to a file :'.$message);
    }
}

class UsersController 
{
    protected $logger;
    
    public function __construct(Logger $logger) 
    {
        $this->logger = $logger;
    }
    
    public function show() 
    {
        $user = 'nahid';
        $this->logger->execute($user);
    }
}

$controller = new UsersController(new LogToDatabase);
$controller->show();

Now If I change from LogToDatabase to LogToFile I do not have to change the constructor method manually. In the constructor method I have Injected an interface; not any arbitrary class. So If you have multiple classes and swap from one class to another class you will get the same result without changing any class references.

In the above example I write a log using LogToDatabase and now I want to write log using LogToFile, I can call it in this way

$controller = new UsersController(new LogToFile);
$controller->show();

I get the result without changing other classes. Because the interface class handles the swapping issue.

Abstract class

An abstract class is a class that is only partially implemented by the programmer. It contains at least one abstract method, which is a method without any actual code in it, just the name and the parameters, and that has been marked as โ€œabstractโ€.

An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class. Here is the example :

<?php
abstract class AbstractClass
{
    // Force Extending class to define this method
    abstract protected function getValue();
    
    public function printOut() 
    {
        print $this->getValue() . "\n";
    }
}

Now the question is when will the situation that a method will be needed and must be implemented? Here I will try to explain. Please see the Tea class.

<?php
class Tea 
{
    public function addTea()
    {
        var_dump('Add proper amount of tea');
        return $this;
    }
    protected  function  addHotWater()
    {
        var_dump('Pour Hot water into cup');
        return $this;
    }
    
    protected  function addSugar()
    {
        var_dump('Add proper amount of sugar');
        return $this;
    }
    
    protected function addMilk()
    {
        var_dump('Add proper amount of Milk');
        return $this;
    }
    
    public function make()
    {
        return $this
            ->addHotWater()
            ->addSugar()
            ->addTea()
            ->addMilk();
    }
}

$tea = new Tea();
$tea->make();

Now we look at the coffee class.

<?php
class Coffee 
{
    public function addCoffee()
    {
        var_dump('Add proper amount of tea');
        return $this;
    }
    
    protected  function  addHotWater()
    {
        var_dump('Pour Hot water into cup');
        return $this;
    }
    
    protected  function addSugar()
    {
        var_dump('Add proper amount of sugar');
        return $this;
    }
    
    protected function addMilk()
    {
        var_dump('Add proper amount of Milk');
        return $this;
    }
    
    public function make()
    {
        return $this
            ->addHotWater()
            ->addSugar()
            ->addCoffee()
            ->addMilk();
    }
}

$tea = new Coffee();
$tea->make();

In the above two classes the three methods addHotWater(), addSugar(), and addMilk() are same. So we should remove duplicated code. We can do it in the following way :

abstract class Template
{
    public function make()
    {
        return $this
            ->addHotWater()
            ->addSugar()
            ->addPrimaryToppings()
            ->addMilk();
    }
    
    protected  function  addHotWater()
    {
        var_dump('Pour Hot water into cup');
        return $this;
    }
    
    protected  function addSugar()
    {
        var_dump('Add proper amount of sugar');
        return $this;
    }
    
    protected function addMilk()
    {
        var_dump('Add proper amount of Milk');
        return $this;
    }
    
    protected abstract function addPrimaryToppings();
}

class Tea extends Template
{
    public function addPrimaryToppings()
    {
        var_dump('Add proper amount of tea');
        return $this;
    }
}

$tea = new Tea();
$tea->make();

class Coffee extends Template
{
    public function addPrimaryToppings()
    {
        var_dump('Add proper amount of Coffee');
        return $this;
    }
}

$coffee = new Coffee();
$coffee->make();

I make an abstract class and name it Template. Here I define addHotWater(), addSugar() and addMilk(); and make an abstract method named addPrimaryToppings.

Now If I make the Tea class extend the Template class then I will get the three defined methods and must define the addPrimaryToppings() method. In a similar way the coffee class will as well.

I have published this article in the medium. if youโ€™d like to read from the medium blog site, please go to this link

Thanks for reading.

More Repositories

1

solid-principles

SOLID Principles - simple and easy explanation
PHP
260
star
2

laravel-docker-k8s

Running Laravel project using Docker and Deploying using Kubernetes
PHP
141
star
3

laravel-pdf

A Simple package for easily generating PDF documents from HTML. This package is specially for laravel but you can use this without laravel.
PHP
86
star
4

git-flow-example

Git Flow Example
PHP
57
star
5

laravel-gentelella

Laravel with Gentelella admin template for developing Laravel applications
PHP
40
star
6

laravel-service-container

Laravel Service Container
PHP
33
star
7

laravel-jwt

Laravel with JWT Authentication for API development
PHP
31
star
8

lumen-jwt-api

Lumen with JWT Authentication for API development
PHP
28
star
9

laravel-docker-redis

Simple example: How to use laravel and redis using docker compose
PHP
27
star
10

eloquent-filter

This simple package helps you filter Eloquent data using query filters.
PHP
25
star
11

laravel-docker-elasticsearch

This is a simple repo for practicing elasticsearch with laravel and docker.
PHP
20
star
12

nodejs-weather-app

Node Js Weather App is a simple module for obtaining weather information
JavaScript
16
star
13

laravel-passport-api

Laravel with Passport Authentication for API development
PHP
13
star
14

laravel-macros

A Simple package for using Macros in Laravel
PHP
9
star
15

designPattern

Design Pattern - simple and easy explanation
PHP
7
star
16

simplex

The Simplex Framework is very simple and easy. It will be very helpful for the developers who are the beginner in PHP and want to learn Framework
PHP
5
star
17

laravel-eloquent-query-filtering

Laravel Eloquent Query Filtering
PHP
5
star
18

basic-problems-and-solutions

Basic data structures and algorithm related problems and solutions
PHP
5
star
19

react-redux-todo

Simple Todo App using react and redux
JavaScript
4
star
20

symfony-4-spacebar

PHP
4
star
21

code-refactore-rules

Code Refactore Rules
PHP
4
star
22

simple-php-framework

Trying to develop basic framework structure using symfony component
PHP
4
star
23

nodejs

JavaScript
3
star
24

vue-vuex-todo

Simple Todo App using Vue and Vuex
PHP
3
star
25

rest-go

Simple api using go
Go
3
star
26

elixir-practise

Elixir Practise
Elixir
3
star
27

laravel-google-spreadsheet

This package is underdeveloped
PHP
2
star
28

curl-vs-guzzle

Curl vs Guzzle
PHP
2
star
29

react-scoreboard

Score Board using React
JavaScript
2
star
30

django

Python
2
star
31

vuejs

HTML
2
star
32

Vue-2.0-Examples

Vue-2.0-Examples
HTML
2
star
33

csv_parse_zf1.12

PHP
2
star
34

elixir-in-examples

Elixir in Examples
Elixir
2
star
35

go-example

Go
2
star
36

symfony-demo

Symfony demo project for learning and practise
PHP
2
star
37

timezones

This package is underdeveloped
PHP
1
star
38

cake-php-demo

CakePHP demo project for learning purpose
PHP
1
star
39

laravel-and-vue

Laravel and Vue Js
PHP
1
star