如何在 Laravel 5 中调用自定义助手?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43179978/
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-09-14 15:42:32  来源:igfitidea点击:

How to call custom helper in laravel 5?

phplaravel

提问by Reynald Henryleo

I wanna make my very own helper, and i put it in app/http/helpers.php. This is my helper code:

我想做我自己的帮手,我把它放进去app/http/helpers.php。这是我的帮助代码:

<?php

namespace App\Helpers;
use Auth;
class helper {

    public static function is_login() {
        if(Auth::check()){
           return True;
        }else{
           return False;
        }
    }

    public static function must_login(){
        if(Auth::check()){
           return True;
        }else{
           return Redirect::to('logout');;
        }
    }
}

?>

and this is my app.php code:

这是我的 app.php 代码:

  'aliases' => [
                'customhelper'=> App\Helpers\Helper::class
               ]

when i use for my blade file customhelper::is_login()it work. But when i try to use in my controller customhelper::must_login()it doesn't work and i've got some error

当我用于刀片文件时,customhelper::is_login()它可以工作。但是当我尝试在我的控制器中使用customhelper::must_login()它时它不起作用并且我遇到了一些错误

Class 'App\Http\Controllers\customhelper' not found

找不到类“App\Http\Controllers\customhelper”

回答by Erol KESK?N

Use your alias with the same name of Helper Class and add use statement to Controller file.

使用与 Helper Class 同名的别名并将 use 语句添加到 Controller 文件中。

For Example :

例如 :

app/Helpers/Helper.php

app/Helpers/Helper.php

<?php
namespace App\Helpers;

class Helper{
    public static function SayHello()
    {
        return "SayHello";
    }
}

config/app.php

config/app.php

'aliases' => [
    /*Defaults...*/
    'Helper' => App\Helpers\Helper::class, 
],

app/Http/Controllers/MyController.php

app/Http/Controllers/MyController.php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use Helper; // Important

class MyController extends Controller
{
    public function index()
    {
        return Helper::SayHello();
    }
}

回答by PHP Team

@Reynald Henryleo

@雷纳德·亨利利奥

First thing like you have mentioned 'app/http/helpers.php'your helper file path in that case your namespace should be 'namespace App\Http'.

喜欢你的第一件事提到'app/http/helpers.php'在这种情况下,你的命名空间应该是你的帮手文件路径'namespace App\Http'

for better understanding to make global helper function refer 'Custom Classes in Laravel 5, the Easy Way'section of Best practices for custom helpers on Laravel 5

为了更好地理解使全局助手功能,请参阅Laravel 5上自定义助手最佳实践的“Laravel 5 中的自定义类,简单方法”部分