加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP接口的最佳实践:我应该只记录接口吗?

发布时间:2020-12-13 17:48:53 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试标准化 PHP接口的文档.最佳做法是仅在接口中维护方法头吗?例如,对于此接口: interface FooInterface { /** * This will test the system in some special way * @param string $sName * @param integer $iCount * @return void */ public functi
我正在尝试标准化 PHP接口的文档.最佳做法是仅在接口中维护方法头吗?例如,对于此接口:

interface FooInterface {

    /** 
     * This will test the system in some special way
     * @param string $sName
     * @param integer $iCount
     * @return void
     */
    public function testMe ($sName,$iCount);
}

我会跳过实现中的方法头文档:

class Foo implements FooInterface {

    /**
     * @see FooInterface::testMe
     */
    public function testMe ($sName,$iCount) {
        // implementation here
    }
}

或者在接口和实现中记录参数是否更好?例如.

class Foo implements FooInterface {

    /**
     * @see FooInterface::testMe
     * @param string $sName
     * @param integer $iCount
     * @return void
     */
    public function testMe ($sName,$iCount) {
        // implementation here
    }
}

通常我更喜欢最小化重复和维护,但也许有充分的理由在两个地方存储参数和返回值的头文档?

解决方法

当使用 phpDocumentor时,@ inheritdoc注释是一个好主意,正如@Scalable所建议的那样.此(已修复) bug tracker issue确认@inheritdoc注释也适用于已实现的接口.

稍微扩展一下:

通常,方法注释应该描述方法的作用[1].通常,由接口定义的方法的所有实现应该执行相同的操作(并且仅在它们的实现方面不同).考虑到这一点,我建议如下:

>使用接口定义中的方法注释来描述该方法应该执行的操作:

interface UserRepository {
    /**
     * Returns all existing users (duh! usually,you'd omit a comment 
     * like this because the method signature is already self-explanatory).
     *
     * @return User[]
     */
    public function findAllUsers();
}

>在实现类的方法注释中使用@inheritdoc注释,并在必要时提供其他特定于实现的详细信息:

class RemoteUserRepository implements UserRepository{
    /**
     * {@inheritdoc}
     *
     * This is achieved by performing a SOAP call to Service XYZ.
     * For performance reasons,results will be cached for 24 hours.
     * Blah,blah,blah.
     */
    public function findAllUsers() {
        // here be dragons
    }
}

>旁注:如果你需要记录你的方法是如何做的,它可能过于复杂,应该分解成更小的单位.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读