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 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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.