1

Recently I came across interface from "Laravel 4 From Apprentice to Artisan" book with the example like this:

interface UserRepositoryInterface {
    public function all();
}

class DbUserRepository implements UserRepositoryInterface {
    public function all()
    {
        return User::all()->toArray();
    }
} 

What is interface? Where to put the interface file?

2
  • You can read about interfaces in the PHP Docs or just do a search on Google. As for where to place the files there's no specific convention, although it's good practice to group files containing common functionality in the same directory (have a look at Laravel's module structure in your vendor directory). Commented Nov 10, 2014 at 8:29
  • As for what interfaces are, I suggest reading on OOP - and the PHP manual on how they're implemented in php. As for where to put it, well, it depends on you: i usually create an "interface" folder, add it to the autoloaded directories, and put it there. Commented Nov 10, 2014 at 8:29

1 Answer 1

5

A Interface is a "contract" between itself and any class that implements the interface. The contract states that any class that implements the interface should have all methods defined in the interface. In this case DbUserRepository has to have a method named "all()" or a fatal error will occur when the class is instantiated.

The Interface file can be placed anywhere but the easiest is to put it in the same directory as the class that implements it.

The purpose of the interface is as follows: Say you want to change your app from using a database (and Eloquent) and now instead you are going store data in JSON files and write your own methods for interacting with your JSON files. Now you can create a new repository e.g. JSONRepository and have it implement UserRepositoryInterface and because the interface forces you to define all the same methods that is defined in the interface, you can now be sure that your app will continue to work as it did. All this without you having to modify existing code.

The database example doesn't really make much real world sense to me because it is unlikely that I would change my storage system so drastically and the example always makes it seem like interfaces only have this one very small use case, which cant be further from the truth. Coding to a interface has many benefits for you and your application.

Another example of interfaces in use can be:

Let's say you have a Calculator class and initially it has two operations it can perform (addition and multiplication). But a few weeks later you need to add another operation (e.g. subtraction), now normally this would mean you have to modify the calculator class and thus risk breaking it. But if you are using a interface you can just create the Subtraction class and have it implement the CalculationInterface and now your app has a new operation without you touching existing code.

Example:

Calculator.php

<?php 

class Calculator {

    protected $result = null;
    protected $numbers = [];
    protected $calculation;

    public function getResult()
    {
        return $this->result;
    }

    public function setNumbers()
    {
        $this->numbers = func_get_args();
    }

    public function setCalculation(CalculationInterface $calculation)
    {
        $this->calculation = $calculation;
    }


    public function calculate()
    {
        foreach ($this->numbers as $num)
        {
            $this->result = $this->calculation->run($num, $this->result);
        }

        return $this->result;
    }


}

CalculationInterface.php

<?php 

interface CalculationInterface {

    public function run($num, $current);
}

Addition.php

<?php 

class Addition implements CalculationInterface {

    public function run($num, $current)
    {
        return $current + $num;
    }
}

Multiplication.php

<?php 

class Multiplication implements CalculationInterface {

    public function run($num, $current)
    {
        /* if this is the first operation just return $num
            so that we don't try to multiply $num with null */
        if (is_null($current))
            return $num;

        return $current * $num;
    }
}

Then to run the calculate method:

$this->calc = new Calculator;
$this->calc->setNumbers(5, 3, 7, 10);
$this->calc->setCalculation(new Addition);
$result = $this->calc->calculate(); //$result = 25 

Now if you want to add a new operation let's say Subtraction you just create the Subtraction class and have it implement the CalculationInterface:

<?php 

class Subtraction implements CalculationInterface {

    public function run($num, $current)
    {

        /* if this is the first operation just return $num
        so that we don't try to subtract from null */
        if (is_null($current))
            return $num;

        return $current - $num;
    }
}

Then to run it:

$this->calc = new Calculator;
$this->calc->setNumbers(30, 3, 7, 10);
$this->calc->setCalculation(new Subtraction);
$result = $this->calc->calculate(); //$result = 10 

So in this example you are breaking your functionality up into smaller classes so that you can add, remove or even change them without breaking something else.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.