Заставить класс, реализующий интерфейс, определить константу

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?

7 голосов | спросил Vladimir Hraban 16 FebruaryEurope/MoscowbMon, 16 Feb 2015 16:50:15 +0300000000pmMon, 16 Feb 2015 16:50:15 +030015 2015, 16:50:15

0 ответов


Похожие вопросы

Популярные теги

security × 330linux × 316macos × 2827 × 268performance × 244command-line × 241sql-server × 235joomla-3.x × 222java × 189c++ × 186windows × 180cisco × 168bash × 158c# × 142gmail × 139arduino-uno × 139javascript × 134ssh × 133seo × 132mysql × 132