Best Practices for Custom Helpers in Laravel 5

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

    Create custom helpers’ directory: First create Helpers directory in app directory. Create hlper class definition: Let’s now create a simple helper function that will concatenate two strings. Create a new file MyFuncs.php in /app/Helpers/MyFuncs.php Add the following code

    namespace App\Helpers; defines the Helpers namespace under App namespace. class MyFuncs {…} defines the helper class MyFuncs. public static function full_name($first_name,$last_name) {…} defines a static function that accepts two string parameters and returns a concatenated string

    Helpers service provide class

    Service providers are used to auto load classes. We will need to define a service provider that will load all of our helper classes in /app/Helpers directory.

    Run the following artisan command:

    php artisan make:provider HelperServiceProvider

    The file will be created in /app/Providers/HelperServiceProvider.php

    Open /app/Providers/HelperServiceProvider.php
    

    Add the following code:

    HERE,

    namespace App\Providers; defines the namespace provider
    use Illuminate\Support\ServiceProvider; imports the ServiceProvider class namespace
    class HelperServiceProvider extends ServiceProvider {…} defines a class HelperServiceProvider that extends the ServiceProvider class
    public function boot(){…} bootstraps the application service
    public function register(){…} is the function that loads the helpers
    foreach (glob(app_path().'/Helpers/*.php') as $filename){…} loops through all the files in /app/Helpers directory and loads them.
    

    We now need to register the HelperServiceProvider and create an alias for our helpers.

    Open /config/app.php file

    Locate the providers array variable

    Add the following line

    App\Providers\HelperServiceProvider::class,
    

    Locate the aliases array variable

    Add the following line

    'MyFuncs' => App\Helpers\MyFuncs::class,
    

    Save the changes Using our custom helper

    We will create a route that will call our custom helper function Open /app/routes.php

    Add the following route definition

    Route::get('/func', function () {
        return MyFuncs::full_name("John","Doe");
    });
    

    HERE,

    return MyFuncs::full_name("John","Doe"); calls the static function full_name in MyFuncs class
    

提交回复
热议问题