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

view.blade.php

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

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


当前回答

我知道现在回答这个问题已经很晚了,但是,这个问题每天都发生在所有初级开发人员身上,所以对于直接步骤,请执行以下步骤:

**将你的helper函数分组到类中(使用刀片中的函数只是使它们静态),并将所有类放在配置Laravel文件夹app.php别名

'aliases' => [
  "YourClassName" => App\Support\YourClassName,
]

现在你可以在刀片和控制器上使用所有的静态函数了。

其他回答

不需要包含您的自定义helper类,实际上可以在别名下添加到config/app.php文件中。

应该是这样的。

 'aliases' => [ 
    ...
    ...
    'Helper' => App\Http\Services\Helper::class,
 ]

然后到你的控制器,使用'use Helper'方法包括Helper,这样你就可以简单地在你的Helper类上调用一些方法。

eg. Helper::some_function();

或者在资源视图中,您可以直接调用Helper类。

eg. {{Helper::foo()}}

但这仍然是开发人员应该遵循的编码风格。我们可能有不同的解决问题的方法,我也想把我的方法分享给初学者。

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中的自定义类,简单方法

首先在App\Helpers\Helper.php中创建你的Helper文件/类 就像:

<?php

namespace App\Helpers;

class Helper {

    // Your customer public function
}

然后在Composer.json中定义它 在交通量 然后运行composer dump-autoload

我最初的想法是作曲家的自动加载,但它对我来说不太像Laravel 5。L5大量使用了服务提供者,它们引导你的应用程序。

首先,我在我的应用程序目录中创建了一个名为Helpers的文件夹。然后在Helpers文件夹中,我为我想添加的功能添加了文件。在一个文件夹中放置多个文件可以避免一个大文件变得太长而难以管理。

接下来,我通过运行artisan命令创建了一个HelperServiceProvider.php:

artisan make:provider HelperServiceProvider

在register方法中,我添加了这个代码片段

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

最后,在config/app.php的providers数组中注册服务提供者

'providers' => [
    'App\Providers\HelperServiceProvider',
]

现在,您的Helpers目录中的任何文件都已加载,并准备使用。

更新2016-02-22

There are a lot of good options here, but if my answer works for you, I went ahead and made a package for including helpers this way. You can either use the package for inspiration or feel free to download it with Composer as well. It has some built in helpers that I use often (but which are all inactive by default) and allows you to make your own custom helpers with a simple Artisan generator. It also addresses the suggestion one responder had of using a mapper and allows you to explicitly define the custom helpers to load, or by default, automatically load all PHP files in your helper directory. Feedback and PRs are much appreciated!

composer require browner12/helpers

Github:布朗纳12/助手

**

地位的助手

** 创建新助手

<?php

namespace App\Helpers;

use Illuminate\Database\Eloquent\Collection;

class StatusHelper
{
 protected static $_status = [
        1=> [
            'value' => 1,
            'displayName' => 'Active',
        ],
        2 => [
            'value' => 2,
            'displayName' => 'Inactive',
        ],
        3 => [
            'value' => 3,
            'displayName' => 'Delete',
        ],

    ];

     public static function getStatusesList()
    {
        $status = (new Collection(self::$_status))->pluck('displayName', 'value')->toArray();


        return $status;
    }
}

用于控制器和任何视图文件

use App\Helpers\StatusHelper;

class ExampleController extends Controller
{
        public function index()
        {
            $statusList = StatusHelper::getStatusesList();

            return view('example.index', compact('statusList'));
        }
}