【问题标题】:Unable to use helper in controller of laravel app无法在 laravel 应用程序的控制器中使用帮助程序
【发布时间】:2015-12-07 00:49:28
【问题描述】:

我正在构建一个应用程序,现在我创建了一个助手

class Students{
    public static function return_student_names()
    {
        $_only_student_first_name = array('a','b','c');
        return $_only_student_first_name;
    }
}

现在我无法在控制器中做这样的事情

namespace App\Http\Controllers;
    class WelcomeController extends Controller
    {
        public function index()
        {
            return view('student/homepage');
        }
        public function StudentData($first_name = null)
        {
            /* ********** unable to perform this action *********/
            $students = Student::return_student_names();
            /* ********** unable to perform this action *********/
        }
    }

这是我的辅助服务提供者

namespace App\Providers;

use Illuminate\Support\ServiceProvider;


class HelperServiceProvider extends ServiceProvider
{

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

i 事件将其作为别名添加到 config/app.php 文件中

'Student' => App\Helpers\Students::class,

【问题讨论】:

  • 有什么错误吗?例外?

标签: php laravel-5 laravel-helper


【解决方案1】:

尝试将use App\Helpers\Student; 放在控制器顶部的命名空间声明下方:

namespace App\Http\Controllers;

use App\Helpers\Student;

class WelcomeController extends Controller
{
    // ...

多看PHPnamespaces以及它们是如何使用的,相信你可能对它们了解不足。它们的唯一目的是让您可以命名和使用两个具有相同名称的类(例如App\Helpers\StudentApp\Models\Student)。如果您需要在同一个源文件中使用这两个类,您可以像这样为其中一个类设置别名:

use App\Helpers\Student;
use App\Models\Student as StudentModel;

// Will create an instance of App\Helpers\Student
$student = new Student(); 
// Will create an instance of App\Models\Student
$student2 = new StudentModel(); 

您确实不需要为此需要服务提供商,只需正常的语言功能即可。如果您想将 Student 对象的构建推迟到 IoC,您需要一个服务提供者:

public function register()
{
    $app->bind('App\Helpers\Student', function() {
        return new \App\Helpers\Student;
    });
}

// ...
$student = app()->make('App\Helpers\Student');

您永远不必在 laravel 中 includerequire 类文件,因为这是 composer 提供的功能之一。

【讨论】:

    【解决方案2】:

    您不需要服务提供商来使其工作。让学生像你一样上课:

    class Students{
        public static function return_student_names()
        {
            $_only_student_first_name = array('a','b','c');
            return $_only_student_first_name;
        }
    }
    

    它的所有方法都应该是静态的

    您正确添加了外观:

    'Student' => App\Helpers\Students::class,
    

    最后,您的问题似乎是由于忘记了外观名称处的反斜杠造成的。使用\Students 而不是Students

    public function StudentData($first_name = null)
    {
        $students = \Student::return_student_names();
    }
    

    当使用门面时,没有必要不包含,门面是为了避免复杂的包含在任何地方。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多