【发布时间】:2018-11-10 17:43:33
【问题描述】:
我正在使用 Laravel 5.4 我正在创建一个服务提供者只是为了测试。我的目标是创建我的 TestClass 的一个实例,并让它在测试控制器中说 Hello World。我已经成功注册了我的服务提供者,但是当我尝试实例化我的 TestClass 时,我得到一个 Class not found 错误。
配置/app.php
Test\Providers\MyTest\TestServiceProvider::class,
TestServiceProvider.php
namespace Test\Providers\MyTest;
use Illuminate\Support\ServiceProvider;
use Test\Services\TestClass;
class TestServiceProvider extends ServiceProvider
{
public function boot()
{
}
public function register()
{
$this->app->bind('Test\Services\TestClass', function ($app) {
return new TestClass();
});
}
}
TestClass.php
namespace Test\Services;
class TestClass
{
public function SayHi()
{
return "Hello World";
}
}
TestController.php
...
use Test\Services\TestClass;
...
class TestController extends Controller
{
public function serviceProviderTest()
{
$words = 'words';
$testClass = new TestClass();
$words = $testClass->SayHi();
return view('test.serviceProviderTest', array(
'words' => $words
));
}
...
}
这给了我以下错误:
未找到 FatalThrowableError 类“Test\Services\TestClass”
如果我注释掉
// $testClass = new TestClass();
// $words = $testClass->SayHi();
我没有收到任何错误,并且按预期在我的视图中看到“单词”。
为什么找不到我的TestClass?
任何帮助将不胜感激!
【问题讨论】:
-
不确定错误是什么,但您实际上并没有使用控制器中服务提供者中注册的对象。您需要使用
app(TestClass::class)而不是new TestClass() -
@PhilCross
app(TestClass::class)需要在服务提供者或控制器中吗? -
控制器。当您在服务提供者中注册课程时,您正在使用
Container注册课程。当你使用函数app()时,它只是从容器内抓取东西的捷径。
标签: php laravel service-provider