Best Practices for Custom Helpers in Laravel 5

后端 未结 20 2392
暖寄归人
暖寄归人 2020-11-22 06:40

I would like to create helper functions to avoid repeating code between views in Laravel 5:

view.blade.php

Foo Formated text: {{ fo

20条回答
  •  感动是毒
    2020-11-22 07:24

    Having sifted through a variety of answers on SO and Google, I still couldn't find an optimal approach. Most answers suggest we leave the application and rely on 3rd party tool Composer to do the job, but I'm not convinced coupling to a tool just to include a file is wise.

    Andrew Brown's answer came the closest to how I think it should be approached, but (at least in 5.1), the service provider step is unnecessary. Heisian's answer highlights the use of PSR-4 which brings us one step closer. Here's my final implementation for helpers in views:

    First, create a helper file anywhere in your apps directory, with a namespace:

    namespace App\Helpers;
    
    class BobFinder
    {
        static function bob()
        {
            return 'Bob?! Is that you?!';
        }
    }
    

    Next, alias your class in config\app.php, in the aliases array:

    'aliases' => [
        // Other aliases
        'BobFinder' => App\Helpers\BobFinder::class
    ]
    

    And that should be all you need to do. PSR-4 and the alias should expose the helper to your views, so in your view, if you type:

    {!! BobFinder::bob() !!}
    

    It should output:

    Bob?! Is that you?!
    

提交回复
热议问题