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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP接口的最佳实践:我应该只记录接口吗?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试标准化 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
    }
}

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

脚本宝典总结

以上是脚本宝典为你收集整理的PHP接口的最佳实践:我应该只记录接口吗?全部内容,希望文章能够帮你解决PHP接口的最佳实践:我应该只记录接口吗?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。