我試圖使用單身人士爲特定的類。Laravel 5.2中的遷移文件中不依賴注入依賴注入
我這樣做平凡使用的「AppServicePrvider.php」以下內容:
<?php
namespace App\Providers;
use App\Helpers\ApplicationFormHelper;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
}
public function register()
{
$this->app->singleton(ApplicationFormHelper::class, function ($app) {
return new ApplicationFormHelper();
});
}
}
我遂把這個類在我的移民文件,像這樣:
<?php
use App\Helpers\ApplicationFormHelper;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
private $applicationFormHelper;
public function __construct(ApplicationFormHelper $applicationFormHelper)
{
$this->applicationFormHelper = $applicationFormHelper;
}
public function up()
{
//...
}
public function down()
{
Schema::drop('users');
}
}
然而,當我執行php artisan migrate
我得到以下錯誤,表明依賴注入不起作用。
[Symfony\Component\Debug\Exception\FatalThrowableError]
Type error: Argument 1 passed to CreateUsersTable::__construct() must be an instance of App\Helpers\ApplicationFor
mHelper, none given, called in /home/vagrant/saroia/vendor/laravel/framework/src/Illuminate/Database/Migrations/Mi
grator.php on line 335
請注意,我已經使用這個類是其他地方(如在路徑文件中)沒有問題。似乎只有在遷移文件中存在此問題!
是的,我需要的是單身。那麼如何執行依賴注入呢? –