Reputation: 6949
Do some of you here on Stack Overflow think that this could be a good implementation or not?
For example I have an interface called RequestInterface
which has 5 constants:
interface RequestInterface {
const GET = 1;
const POST = 2;
const PUT = 3;
const DELETE = 4;
const HEAD = 5;
public function getType();
// ... some other methods declarations
}
And then for each constant a class which implements that interface, e.g. the PostRequest
:
class PostRequest implements RequestInterface {
public function getType() {
return RequestInterface::POST
}
}
The PUT request:
class PutRequest implements RequestInterface {
public function getType() {
return RequestInterface::PUT
}
}
And so for the other classes.
I know that using constants inside an interface is considered an Anti-Pattern by some, but what would you say about the example I made, and what could be a possible better solution for such a case?
EDIT: @pid you advise me to use the get_class() or is_a() function, so e.g. if I have another class which uses that RequestInterface I could get rid of those constants and simply use even instanceof to determine the type of the RequestInterface?
// inside another class which uses a RequestInterface
public function someMethod(RequestInterface $request) {
if ($request instanceof PostRequest) {
// Request is a post...
}
}
Upvotes: 4
Views: 3303
Reputation: 11607
Consider that the interface definition is most likely exposed to a client application. You don't want to have implementation details in that file. A client programmer wants to look at your interface definition and just see what matters, that is the API contract of which the meaning has been described in the documentation.
The actual value of the constants has no importance whatsoever. In fact, exposing this by putting it in the interface definition nullifies the usage of constants... ignore the actual values in favor of mnemonic/onomatopoeic terms (onomato... => it is what it sounds like, no documentation/explanation needed to understand it straight away).
Upvotes: 2