How do I make global helper functions in laravel 5

2019-01-16 16:31发布

If I wanted to make a currentUser() function for some oauth stuff I am doing where I can use it in a view or in a controller (think rails, where you do helper_method: current_user in the application controller).

Everything I read states to create a helpers folder and add the function there and then that way you can do Helpers::functionName Is this the right way to do this?

Whats the "laravel way" of creating helper functions that can be used in blade templates and controllers?

3条回答
Animai°情兽
2楼-- · 2019-01-16 17:00

Create a new file in your app/Helpers directory name it AnythingHelper.php An example of my helper is :

<?php
function getDomesticCities()
{
$result = \App\Package::where('type', '=', 'domestic')
    ->groupBy('from_city')
    ->get(['from_city']);

return $result;
}

generate a service provider for your helper by following command

php artisan make:provider HelperServiceProvider

in the register function of your newly generated HelperServiceProvider.php add following code

require_once app_path('Helpers/AnythingHelper.php');

now in your config/app.php load this service provider and you are done

'App\Providers\HelperServiceProvider',
查看更多
太酷不给撩
3楼-- · 2019-01-16 17:01

Another efficient way of creating a global functions file is to autoload it directly from composer. The autoload section of composer accepts a files array that is automatically loaded.

  1. Create a functions.php file wherever you like, in this example, we are going to create it inside app/Helpers.

  2. Add your functions, but do not add a class or namespace.

    <?php
    
    function global_function_example($str)
    {
       return 'A Global Function with '. $str;
    }
    
  3. In composer.json inside the autoload section add the following line:

    "files": ["app/Helpers/functions.php"]
    

For Laravel 5:

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": ["app/Helpers/functions.php"]
},
  1. Run composer dump-autoload

Congratulations! You may now access global_function_example('hello world') form any part of your application including Blade views.

I hope this is useful for someone!

查看更多
做个烂人
4楼-- · 2019-01-16 17:13

Laravel global helpers

Often you will find your self in need of a utility function that is access globally throughout you entire application. Borrowing from how laravel writes their default helpers you're able to extend the ability with your custom functions.

Create the helper file, not class

I prefer to you a file and not a class since I dont want to bother with namespaces and I want its functions to be accessible without the class prefixes like: greeting('Brian'); instead of Helper::greeting('Brian'); just like Laravel does with their helpers.

File: app/Support/helper.php

Register helper file with Composer: composer.json

{
    ...
    "autoload": {
        "classmap": [
            "database"
        ],
        "files": [
            "app/Support/helpers.php"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    ...
}

Create your first helper function

<?php

if (!function_exists('greet')) {
    /**
     * Greeting a person
     *
     * @param  string $person Name
     * @return string
     */
    function greet($person)
    {
        return 'Hello ' . $person;
    }
}

Usage:

Remember to autoload the file before trying to access its functions: composer dump-autoload

Let's test with Tinker

$ php artisan tinker
Psy Shell v0.8.17 (PHP 7.0.6 ΓÇö cli) by Justin Hileman
>>> greet('Brian');
=> "Hello Brian"
>>> exit
Exit:  Goodbye.

With Blade

<p>{{ greet('Brian') }}</p>

Advanced usage as Blade directive:

A times you will find yourself wanting to use a blade directive instead of a plain function. Register you Blade directive in the boot method of AppServiceProvider: app/Providers/AppServiceProvider.php

public function boot()
{
    // ...
    Blade::directive('greet', function ($expression) {
        return "<?php echo greet({$expression}); ?>";
    });
}

Usage: <p>@greet('Brian')</p>

Note: you might need to clear cache views php artisan view:clear

查看更多
登录 后发表回答