Search code examples
phplaravellaravel-5laravel-facade

Extend Laravel 5's Response Facade to include further helpers?


I'm trying to allow an user to do something like response()->yaml(['their content']), but I don't understand how I'd go on injecting my YAML method to the response() (ResponseFactory) facade.

Is there any guide that would explain on how to do this? Or maybe a quick description from someone? This is the first time I'm trying to build a package for Laravel and it will also be open source!

I checked out this question, but unfortunately I don't see its use case and I don't think it focuses on adding an additional method which would be called via response().


Solution

  • You can you use Response Macros to achieve your aim.

    In the boot method of your AppServiceProvider (or in the package ServiceProvider) add the following:

    Response::macro('yaml', function ($content) {
        return yaml_whatever($content); //Use your implementaion here
    });
    

    Now, you can use return response()->yaml($content);