Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force a class implementing the interface to define a constant

I am willing to force my classes to define a constant named COMMAND. If php would allow overriding constants from interfaces in would look like

class RequestInterface
{
    const COMMAND = "no-command-specified";
}

class LoginRequest implements RequestInterface
{
    const COMMAND = "loginuser";
    public $username;
    public $password;
}

$request = new LoginRequest();
$request->username = "user";
$request->password = "blah";

Obviously this does not work. I am looking for a clean way to make my requests define COMMAND cosntant.

I've been considering the following options:

  • Interface defines a getCommand method and my request classes need to implement it and return the command name as a string. But it is too much code per request
  • Replace the interface with an abstract class. It looks weird because abstract class is usually expected to define at least one method
  • Interface becomes abstract class and defines a protected variable $command. It also has a getter method that returns $this->command;. Children override protected property $command. I do not like the way of mixing public VARIABLES (that are supposed to be variable) with a protected VARIABLE that is not really supposed to be modifiable and therefore not suppose to be a variable in the first place.

    class LoginRequest extends BaseRequest
    {
         protected $command = "loginuser";
         public $username;
         public $password;
    }
    

What would be the cleanest way of achieving this?

like image 989
Vladimir Hraban Avatar asked Feb 16 '15 13:02

Vladimir Hraban


1 Answers

Personally, my choice would be:

interface RequestInterface
{
    /**
     * @returns string
     */
    public function getCommand();
}

class LoginRequest implements RequestInterface
{
    public function getCommand() {
        return "loginuser";
    }
   ...
}

You can always check that a string is returned with is_string() later. There's nothing to stop someone setting COMMAND to a number anyway.

like image 165
DanielM Avatar answered Sep 29 '22 06:09

DanielM