PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 22, 2022

[FIXED] What's a benefit of empty interface over a class property?

 January 22, 2022     laravel, php     No comments   

Issue

In Laravel, you can indicate that an Event listener should be queued by implementing a ShouldQueue interface, which has no method in it (more on it in the docs). It's also used in a few different places throughout a framework (e.g. in Jobs).

Does it give you some particular benefits compared to using static class properties?

I am taking an EdX course on Software Construction, and TA there claims that (at least in Java) empty interfaces are something that should not be used. Is it different in PHP?


Solution

If we take your example of ShouldQueue this interface can be implemented to indicate in the that a command|event|notification|anything should be pushed to a queue.

We can follow this through to see where this interface is utilised in the command example, and we get to the Dispatcher

protected function commandShouldBeQueued($command)
{
    return $command instanceof ShouldQueue;
}

// Which is called in the dispatch method

public function dispatch($command)
{
    if ($this->queueResolver && $this->commandShouldBeQueued($command)) {
        return $this->dispatchToQueue($command);
    }

    return $this->dispatchNow($command);
}

So it follows that simply by implementing this empty interface, we can change the behaviour of the how the command is dispatched. The Framework then, I would say, uses the interface as an indication of intended behaviours.

I think you can determine that this is clearer than a class constant, because you don't really care which classes implement the interface, just understand that by doing so you're agreeing to a behaviour being possible, even if the specifics of that behaviour aren't mandated by the interface's contract.



Answered By - Luke
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing