【问题标题】:Laravel Service Provider Class Not Found未找到 Laravel 服务提供者类
【发布时间】: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


【解决方案1】:

将新的基本路径添加到您的composer.json

"psr-4": {
     "App\\": "app/",
     "Test\\": "test/"
 },

然后运行:

composer dump-autoload

【讨论】:

  • 这只是绕过了服务提供者。
猜你喜欢
  • 2023-04-01
  • 2015-10-31
  • 1970-01-01
  • 2016-01-02
  • 2016-02-14
  • 2015-09-12
  • 2017-09-20
  • 2014-12-01
  • 1970-01-01
相关资源
最近更新 更多