【问题标题】:How to add custom method to Lumen's response class如何将自定义方法添加到 Lumen 的响应类
【发布时间】:2018-10-24 22:25:20
【问题描述】:

我正在使用响应方法withHeaders():

return response(view('pages.top.index', compact('data')))->withHeaders(['one-param' => 'data', 'second-param' => 'data2' ...);

而且我在withHeaders() 方法中几乎在每个控制器的操作中都有多个相同的参数。有没有办法可以添加自己的方法并将其链接起来:

return response(view('pages.top.index', compact('data')))->customMethod('data', 'data2', ....);

【问题讨论】:

    标签: laravel lumen lumen-5.4


    【解决方案1】:

    响应是可宏的,因此您可以将其添加到服务提供者:

    \Illuminate\Http\Response::macro('customMethod', function () { 
          //Method body
          return $this; //To chain it
    }); 
    

    注意: 我倾向于避免这种情况,因为它让我的 IDE 很难进行类型提示。

    如果问题在于需要一遍又一遍地传递相同的数据,您也可以考虑sharing data with all views

    【讨论】:

    • 对于 Lumen 5.7,电话是\Laravel\Lumen\Http\ResponseFactory::macro
    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 2018-02-26
    • 2021-12-28
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    相关资源
    最近更新 更多