4

AS I was looking at code in Laravel 5 project, I encountered with a class Like below --

class Abc extends Command implements SelfHandling, ShouldBeQueued
{

}

And where Interfaces are like below -

interface SelfHandling {}
interface ShouldBeQueued {}

I got confused if it does not have any methods then what's the use of these interfaces ?

vincenth
  • 1,732
  • 5
  • 19
  • 27
Abhishek
  • 1,543
  • 3
  • 13
  • 29
  • 1
    Possible duplicate of [Interface with no methods](http://stackoverflow.com/questions/20878039/interface-with-no-methods). They call them "[Marker interfaces](https://en.wikipedia.org/wiki/Marker_interface_pattern)". – RandomSeed Aug 09 '16 at 10:47

2 Answers2

1

It allows to handle objects by behavior. Say you have an array of objects implementing different interface, you can then differentiate them doing this :

if($obj instanceof ShouldBeQueued){
    //do something
}
else if{$obj instanceof SelfHandling){
    //do something else
}

This example is a bit crude, but I hope it will help you.

vincenth
  • 1,732
  • 5
  • 19
  • 27
  • so what should be the case if i create an instance of Abc class, Can it be an instance of both ShouldBeQueued and SelfHandling well ? then there is no meaning for if and else if as it will fall in both cases ? – Abhishek Aug 09 '16 at 10:51
  • Bear in mind it is just a crude example. But, you could have objects that implement one, both, or none of this interface and process them accordingly. – vincenth Aug 09 '16 at 11:09
  • Someone came up with a better answer than me : http://wpkrauts.com/2013/how-to-build-flexible-php-interfaces/#interfaces-with-no-methods. In your case, I think it's in order to use internal types – vincenth Aug 09 '16 at 11:14
0

They are used as sort of a "flag". It can be checked by doing $command instanceof ShouldBeQueued.

The alternative would be to include a method, but that would require multiple lines of redundant code. (Most implementations would return true anyway.)

interface ShouldBeQueued
{
    /**
     * @return bool
     */
    function shouldBeQueued();
}

class Abc extends Command implements ShouldBeQueued
{
    function shouldBeQueued()
    {
        return true;
    }
}

Checking it would be a bit more complicated as well:

if ($command instanceof ShouldBeQueued && $command->shouldBeQueued()) { /*...*/ }

Whether it is a good practice is another matter.

Shira
  • 6,392
  • 2
  • 25
  • 27