0

I am using Laravel 5.4 I am creating a Service Provider just for testing. My goal is create an instance of my TestClass and make it say Hello World in a Test Controller. I have successfully registered my service provider, but when I try to instantiate my TestClass I get a Class not found error.

config/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
        ));
    }
    ...
}

This gives me the following error:

FatalThrowableError Class 'Test\Services\TestClass' not found

If I comment out

// $testClass = new TestClass();
// $words = $testClass->SayHi();

I get no errors and I see 'words' in my view as expected.

Why can't my TestClass be found?

Any help would be greatly appreciated!

user908759
  • 1,355
  • 8
  • 26
  • 48
  • Not sure about what the error is, but you're not actually using the object registered in the service provider in your controller. You'd need to do `app(TestClass::class)` instead of `new TestClass()` – Phil Cross May 31 '18 at 16:38
  • @PhilCross does `app(TestClass::class)` need to be in the service provider or controller? – user908759 May 31 '18 at 17:05
  • Controller. When you register classes in service providers, you're registering them with the `Container`. when you use the function `app()`, it's just a shortcut to grabbing things from inside the container. – Phil Cross May 31 '18 at 21:31

1 Answers1

3

Add the new base path into your composer.json:

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

Then run:

composer dump-autoload
Hamed Kamrava
  • 12,359
  • 34
  • 87
  • 125