php 如何在 Laravel 5 中创建全局辅助函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32419619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:57:46  来源:igfitidea点击:

How do I make global helper functions in laravel 5?

phplaravel-5bladecontrollershelpers

提问by TheWebs

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_userin the application controller).

如果我想currentUser()为一些 oauth 的东西创建一个函数,我正在做我可以在视图或控制器中使用它的地方(想想 rails,你helper_method: current_user在应用程序控制器中做的地方)。

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

我阅读的所有内容都表明要创建一个 helpers 文件夹并在那里添加函数,然后您就可以这样做了Helpers::functionName这是正确的方法吗?

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

创建可在刀片模板和控制器中使用的辅助函数的“laravel 方式”是什么?

回答by Khan Shahrukh

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

在您的 app/Helpers 目录中创建一个新文件,将其命名为 AnythingHelper.php 我的助手示例是:

<?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

在新生成的 HelperServiceProvider.php 的注册函数中添加以下代码

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

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

现在在你的 config/app.php 加载这个服务提供者,你就完成了

'App\Providers\HelperServiceProvider',

回答by Arian Acosta

An easy and efficient way of creating a global functions file is to autoload it directly from Composer. The autoload section of composer accepts a filesarray that is automatically loaded.

创建全局函数文件的一种简单有效的方法是直接从 Composer 自动加载它。composer 的自动加载部分接受一个files自动加载的数组。

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

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

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

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

    Example for Laravel 5:

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

  1. functions.php在任何你喜欢的地方创建一个文件。在这个例子中,我们将在 inside 中创建app/Helpers

  2. 添加您的功能,但添加类或命名空间。

    <?php
    
    function global_function_example($str)
    {
       return 'A Global Function with '. $str;
    }
    
  3. composer.jsonautoload部分内添加以下行:

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

    Laravel 5 示例:

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

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

完毕!您现在可以访问global_function_example('hello world')应用程序的任何部分,包括 Blade 视图。

回答by bmatovu

Laravel global helpers

Laravel 全局助手

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.

通常,您会发现自己需要一个可以在整个应用程序中全局访问的实用函数。借鉴 laravel 编写默认助手的方式,您可以使用自定义函数扩展功能。

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.

我更喜欢你一个文件而不是一个类,因为我不想打扰命名空间,我希望它的函数可以在没有类前缀的情况下访问,例如:greeting('Brian');而不是Helper::greeting('Brian');像 Laravel 对它们的助手所做的那样。

File:app/Support/helper.php

文件:app/Support/helper.php

Register helper file with Composer: composer.json

向 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

请记住在尝试访问其功能之前自动加载文件: composer dump-autoload

Let's test with Tinker

让我们用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:

作为 Blade 指令的高级用法:

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

有时您会发现自己想要使用刀片指令而不是普通函数。在 AppServiceProvider 的引导方法中注册您的 Blade 指令:app/Providers/AppServiceProvider.php

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

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

用法:<p>@greet('Brian')</p>

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

注意:您可能需要清除缓存视图 php artisan view:clear

回答by Kefi

Another option, if you don't want to register all your helper functions one by one and wondering how to register them each time you create a new helper function:

另一种选择,如果你不想一个一个地注册所有的辅助函数,并且不知道每次创建一个新的辅助函数时如何注册它们:

Again in the app/Providers/AppServiceProvider.phpadd the following in registermethod

再次在app/Providers/AppServiceProvider.php 中register方法中添加以下内容

public function register()
{
    foreach (glob(app_path().'/Helpers/*.php') as $filename) {
        require_once($filename);
    }
}

回答by f_i

The above answers are great with a slight complication, therefore this answer exists.

上面的答案很好,但有点复杂,因此存在这个答案。

utils.php

实用程序.php

if (!function_exists('printHello')) {

    function printHello()
    {
        return "Hello world!";
    }
}

in app/Providers/AppServiceProvider.phpadd the following in registermethod

app/Providers/AppServiceProvider.php 中register方法中添加以下内容

public function register()
{
   require_once __DIR__ . "/path/to/utils.php"
}

now printHellofunction is accessible anywhere in code-base just as any other laravel global functions.

现在printHello函数可以在代码库中的任何位置访问,就像任何其他 Laravel 全局函数一样。