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

view.blade.php

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

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


当前回答

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

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

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

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

其他回答

在你的app文件夹中创建一个helpers.php文件,并用composer加载它:

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

然后把它添加到你的作曲家。Json文件,执行如下命令:

composer dump-autoload

如果您不喜欢将helpers.php文件保存在app目录中(因为它不是一个PSR-4命名空间类文件),您可以做laravel.com网站所做的事情:将helpers.php存储在bootstrap目录中。记得在你的作曲器中设置它。json文件:

"files": [
    "bootstrap/helpers.php"
]

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

这个答案适用于Laravel中的一般自定义类。有关更多Blade的具体答案,请参阅Laravel 5中的自定义Blade指令。

步骤1:创建您的Helpers(或其他自定义类)文件,并给它一个匹配的名称空间。编写你的类和方法:

<?php // Code within app\Helpers\Helper.php

namespace App\Helpers;

class Helper
{
    public static function shout(string $string)
    {
        return strtoupper($string);
    }
}

步骤2:创建别名:

<?php // Code within config/app.php

    'aliases' => [
     ...
        'Helper' => App\Helpers\Helper::class,
     ...

步骤3:在项目根目录下运行composer dump-autoload

第四步:在你的Blade模板中使用它:

<!-- Code within resources/views/template.blade.php -->

{!! Helper::shout('this is how to use autoloading correctly!!') !!}

额外学分:在你的Laravel应用程序的任何地方使用这个类:

<?php // Code within app/Http/Controllers/SomeController.php

namespace App\Http\Controllers;

use Helper;

class SomeController extends Controller
{

    public function __construct()
    {
        Helper::shout('now i\'m using my helper class in a controller!!');
    }
    ...

来源:http://www.php-fig.org/psr/psr-4/

为什么它可以工作:https://github.com/laravel/framework/blob/master/src/Illuminate/Support/ClassLoader.php

自动装填的来源: http://php.net/manual/en/language.oop5.autoload.php

在app/Helper/Helpers.php中创建Helpers.php

namespace App\Helper
class Helpers
{


}

添加作曲家和作曲家更新

 "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories",
            "database","app/Helper/Helpers.php"
        ],
        "psr-4": {
            "App\\": "app/"
        },
         "files": ["app/Helper/Helpers.php"]
    },

在控制器中使用

use App\Helper\Helpers

视图中使用 修改config->app.php文件

   'aliases' => [
    ...
    'Helpers'   => 'App\Helper\Helpers'
    ],

视图中调用

<?php echo Helpers::function_name();  ?>

创建自定义助手目录: 首先在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