【问题标题】:Describing controller query parameters in PHPDoc在 PHPDoc 中描述控制器查询参数
【发布时间】:2020-07-27 21:53:00
【问题描述】:

我的 Laravel 控制器上有一个 index 方法,它接受一个可选的查询字符串参数。

这应该如何在方法的 PHPDoc 块中表示?

EmployerController.php:

/**
 * @param Request $request
 * @return Response
 * Returns list of Employers
 */
public function index(Request $request) {
    // This is the optional parameter which needs to be represented
    // in the PHPDoc block
    $collectiveAgreement = $request->query('collective_agreement');

    ...
}

【问题讨论】:

    标签: php laravel phpdoc


    【解决方案1】:

    将描述保留在第一行,@param@return 在下面。这将是一种标准顺序。随意添加您想要的描述以及它将如何帮助其他阅读代码的人。在这种情况下,您已经记录了参数,因为该查询字符串是 $request 对象的一部分,但您可以将描述扩展为:

    /**
     * Returns list of Employers. 
     * Request object may have optional query string parameter 'collective_agreement'
     * used for this and this and that and that
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        // This is the optional parameter which needs to be represented
        // in the PHPDoc block
        $collectiveAgreement = $request->query('collective_agreement');
        ...
    }
    

    【讨论】:

    • 技术上正确,但我认为 Kenny Horna 的答案是我所追求的,即使它需要更改代码。
    【解决方案2】:

    如果您的目的是记录这些字段,我建议创建一个处理所有逻辑的 FormRequest,然后将表单请求注入控制器。这样,您就知道请求是在哪里形成的,然后去那个类查看字段,甚至更好:它们通过验证的规则。

    php artisan make:request ListUsersRequest
    

    ListUsersRequest.php

    namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    
    class ListUsersRequest extends FormRequest {
    
        public function rules()
        {
            return [
                'collective_agreement' => ['here', 'goes', 'your', 'rules'],
                'another_field'        => ['here', 'goes', 'more', 'rules'],
            ];
        }
    
        public function authorize()
        {
            return true;
        }
    }
    

    然后,回到你的控制器

    用户控制器.php

    public function index(ListUsersRequest $request)
    {   //                ^^^^^^^^^^^^^^^^
        $data = $request->validated();
        $collectiveAgreement = $data['collective_agreement'];
    //  Or as you did:   
    //  $collectiveAgreement = $request->query('collective_agreement');
    }
    

    【讨论】:

    • 我认为这是正确的答案,唯一的缺点是它使代码比它真正应得的更冗长。您是否有任何可靠示例/文档的链接可以实现您的建议?
    • @KennyHorna 是正确的。这是记录您的 api 的更好方法。这意味着如果将来需要更改那些“可选”参数,您最终会这样做一次,即更改逻辑并且在同一个 Request 类中更改文档。此外,当逻辑发生变化时,文档块文档很容易很快就过时了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多