Best Practices for Custom Helpers in Laravel 5

后端 未结 20 2025
暖寄归人
暖寄归人 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:38

    Custom Classes in Laravel 5, the Easy Way

    This answer is applicable to general custom classes within Laravel. For a more Blade-specific answer, see Custom Blade Directives in Laravel 5.

    Step 1: Create your Helpers (or other custom class) file and give it a matching namespace. Write your class and method:

    Step 2: Create an alias:

     [
         ...
            'Helper' => App\Helpers\Helper::class,
         ...
    

    Step 3: Run composer dump-autoload in the project root

    Step 4: Use it in your Blade template:

    
    
    {!! Helper::shout('this is how to use autoloading correctly!!') !!}
    

    Extra Credit: Use this class anywhere in your Laravel app:


    Source: http://www.php-fig.org/psr/psr-4/

    Why it works: https://github.com/laravel/framework/blob/master/src/Illuminate/Support/ClassLoader.php

    Where autoloading originates from: http://php.net/manual/en/language.oop5.autoload.php

提交回复
热议问题