我想创建帮助函数,以避免在Laravel视图之间重复代码。例如:

view.blade.php

<p>Foo Formated text: {{ fooFormatText($text) }}</p>

它们基本上是文本格式化函数。我应该如何定义全局可用的帮助函数,如fooFormatText()?


当前回答

在dir bootstrap\autoload.php中

require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../app/Helpers/function.php'; //add

添加这个文件

app\Helpers\function.php

其他回答

在SO和谷歌上筛选了各种各样的答案后,我仍然没有找到一个最佳的方法。大多数答案建议我们离开应用程序,依靠第三方工具Composer来完成工作,但我不相信仅仅为了包含一个文件而耦合到一个工具是明智的。

Andrew Brown的回答最接近我认为应该如何处理它,但是(至少在5.1中),服务提供者步骤是不必要的。Heisian的回答强调了PSR-4的使用,这让我们更接近了一步。下面是视图中helper的最终实现:

首先,在你的app目录中创建一个helper文件,命名空间为:

namespace App\Helpers;

class BobFinder
{
    static function bob()
    {
        return '<strong>Bob?! Is that you?!</strong>';
    }
}

接下来,在config\app.php中,在aliases数组中为你的类添加别名:

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

这就是你需要做的。PSR-4和别名应该向你的视图公开helper,所以在你的视图中,如果你输入:

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

它应该输出:

<strong>Bob?! Is that you?!</strong>

Laravel 5自定义刀片指令

是的,还有另一种方法!

第一步:注册一个自定义Blade指令:

<?php // code in app/Providers/AppServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Blade; // <-- This is important! Without it you'll get an exception.

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
     public function boot()
     {
         // Make a custom blade directive:
         Blade::directive('shout', function ($string) {
             return trim(strtoupper($string), '(\'\')');
         });

         // And another one for good measure:
         Blade::directive('customLink', function () {
             return '<a href="#">Custom Link</a>';
         });
     }
    ...

步骤2:使用自定义Blade指令:

<!-- // code in resources/views/view.blade.php -->

@shout('this is my custom blade directive!!')
<br />
@customLink

输出:

这是我的自定义刀片指令!! 自定义链接


来源:https://laravel.com/docs/5.1/blade extending-blade

附加阅读:https://mattstauffer.co/blog/custom-conditionals-with-laravels-blade-directives


如果您想学习如何最好地创建可以在任何地方使用的自定义类,请参阅Laravel 5中的自定义类,简单方法

这是我的HelpersProvider.php文件:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider
{
    protected $helpers = [
        // Add your helpers in here
    ];

    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     */
    public function register()
    {
        foreach ($this->helpers as $helper) {
            $helper_path = app_path().'/Helpers/'.$helper.'.php';

            if (\File::isFile($helper_path)) {
                require_once $helper_path;
            }
        }
    }
}

你应该在app文件夹下创建一个名为Helpers的文件夹,然后在里面创建一个名为whatever.php的文件,并在$ Helpers数组中添加字符串whatever。

完成了!

Edit

我不再使用这个选项,我目前使用作曲家加载静态文件,如帮助。

你可以直接在:

...
"autoload": {
    "files": [
        "app/helpers/my_helper.php",
        ...
    ]
},
...

对于我的Laravel项目中的自定义助手库,我在我的Laravel/App目录中创建了一个名为Libraries的文件夹,在Libraries目录中,我为不同的助手库创建了各种文件。

在创建我的助手文件后,我简单地将所有这些文件包含在我的composer中。这样的Json文件

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

和执行

composer dump-autoload

首先在App\Http目录中创建helpers.php。 然后在composer.json中添加以下代码

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

执行如下命令

composer dump-autoload

现在可以在helpers.php文件中定义自定义函数。