使用带有常量的接口作为类的多态行为的开始是一种好做法吗?


Is it good practice to use an Interface with constants as a start for a polymorphic behaviour of classes?

在座的各位是否认为这可能是一个很好的实现?

例如,我有一个名为RequestInterface的接口,它有5个常量:

interface RequestInterface {
    const GET = 1;
    const POST = 2;
    const PUT = 3;
    const DELETE = 4;
    const HEAD = 5;
    public function getType();
    // ... some other methods declarations
}

然后对于每个常量一个实现该接口的类,例如PostRequest:

class PostRequest implements RequestInterface {
     public function getType() {
          return RequestInterface::POST
     }
}
PUT请求:
class PutRequest implements RequestInterface {
     public function getType() {
          return RequestInterface::PUT
     }
}

其他类也是如此。

我知道在接口中使用常量被一些人认为是一种反模式,但是你对我所做的例子有什么看法?对于这种情况,可能有什么更好的解决方案?

编辑:@pid你建议我使用get_class()或is_a()函数,所以,例如,如果我有另一个类使用的RequestInterface,我可以摆脱这些常量,甚至简单地使用instanceof来确定RequestInterface的类型?

// inside another class which uses a RequestInterface
public function someMethod(RequestInterface $request) {
    if ($request instanceof PostRequest) {
       // Request is a post...
    }
}

考虑接口定义很可能公开给客户机应用程序。您不希望在该文件中包含实现细节。客户端程序员想看看你的接口定义,看看什么是重要的,那就是API契约,其含义在文档中已经描述过了。

常数的实际值并不重要。事实上,通过将其放在接口定义中来暴露它会使常量的使用无效……忽略实际值,使用助记/拟声词(onomato…=>这就是它听起来的样子,不需要文档/解释就能马上理解)。

相关文章: