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

view.blade.php

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

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


当前回答

首先在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/助手

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

在Laravel 5.3及以上版本中,Laravel团队将所有过程文件(routes.php)移出了app/目录,整个app/文件夹是psr-4自动加载的。接受的答案在这种情况下是可行的,但我感觉不对。

所以我所做的就是在我的项目的根目录下创建了一个helpers/目录,并把helper文件放在里面,放在我的composer中。我这样做:

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

这样我的app/目录仍然是psr-4自动加载的,并且帮助程序组织得更好一些。

这是我的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",
        ...
    ]
},
...

创建自定义助手目录: 首先在app目录中创建Helpers目录。 创建hlper类定义: 现在让我们创建一个简单的辅助函数,它将连接两个字符串。在/app/Helpers/MyFuncs.php中创建一个新文件MyFuncs.php

<?php

namespace App\Helpers;

class MyFuncs {

    public static function full_name($first_name,$last_name) {
        return $first_name . ', '. $last_name;   
    }
}

名称空间的应用程序\助手;在App namespace下定义了Helpers命名空间。 类MyFuncs{…}定义了帮助类MyFuncs。 公共静态函数full_name($first_name,$last_name){…}定义了一个静态函数,它接受两个字符串形参并返回一个连接的字符串

帮工服务提供类

服务提供者用于自动加载类。我们需要定义一个服务提供者,它将加载/app/Helpers目录下的所有helper类。

执行以下artisan命令:

php工匠使:提供者HelperServiceProvider

该文件将创建在/app/Providers/HelperServiceProvider.php中

Open /app/Providers/HelperServiceProvider.php

添加如下代码:

<?php 

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider {

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

   /**
    * Register the application services.
    *
    * @return void
    */
   public function register()
   {
        foreach (glob(app_path().'/Helpers/*.php') as $filename){
            require_once($filename);
        }
   }
}

在这里,

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.

现在我们需要注册HelperServiceProvider并为我们的助手创建一个别名。

打开/config/app.php文件

找到providers数组变量

添加以下行

App\Providers\HelperServiceProvider::class,

定位aliases数组变量

添加以下行

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

保存更改 使用我们的自定义助手

我们将创建一个调用自定义帮助函数Open /app/routes.php的路由

添加以下路由定义

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

在这里,

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