0

アプリケーションを構築していますが、今はヘルパーを作成しています

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);
        }
    }
}

config/app.php ファイルにエイリアスとしてイベントを追加しました

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

4

2 に答える 2

1

use App\Helpers\Student;名前空間の宣言の下にコントローラーの上部を配置してみてください。

namespace App\Http\Controllers;

use App\Helpers\Student;

class WelcomeController extends Controller
{
    // ...

PHP名前空間とその使用方法を詳しく調べてください。それらについて十分に理解していない可能性があると思います。それらの唯一の目的は、同じ名前の 2 つのクラスに名前を付けて使用できるようにすることです (例: App\Helpers\Studentvs Maybe App\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');

includeそれはcomposerrequireが提供する機能の1つであるため、laravelでクラスファイルを作成する必要はありません。

于 2015-09-10T16:34:07.007 に答える