Sheldon
Sheldon

Reputation: 10105

Why am I getting class not found? (Laravel, PHP)

I'm trying to add a binding to the register method in my ServiceProvider but I keep getting this error:

{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'MyApp\\Providers\\App' not found","file":"\/Users\/foobar\/Dropbox\/Staff Folders\/foobar\/htdocs\/bla\/test\/app\/MyApp\/Providers\/TestServiceProvider.php","line":14}}

composer.json:

"psr-0": {
   "MyApp": "app/"
 }

app/MyApp/TestServiceProvider.php:

<?php namespace MyApp\Providers;

use Illuminate\Support\ServiceProvider;

class TestServiceProvider extends ServiceProvider {

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        App::bind('payment', function()
        {
            return new \app\MyApp\Providers\Payment;
        });
    }
}
?>

app/MyApp/Payment.php:

<?php namespace MyApp\Providers;

class Payment{

    public function process()
    {
        //
    }

}


?>

How do I get this to work?

Upvotes: 0

Views: 853

Answers (2)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111899

There are at least 2 error here.

First error (the one you showed in your question) is:

App::bind('payment', function()
{
    return new \app\MyApp\Providers\Payment;
});

Because your file is MyApp\Providers namespace, you need to use:

\App::bind instead of App:bind here or add use App; after your namespace this way:

<?php namespace MyApp\Providers;

    use App;

The second error is the one that @Bogdan mentioned. Instead of:

return new \app\MyApp\Providers\Payment;

you should use:

return new \MyApp\Providers\Payment;

but because those 2 classes are in the same namespace you can use here:

return new Payment;

Upvotes: 1

Bogdan
Bogdan

Reputation: 44586

Your Payment class binding should return this:

return new \MyApp\Providers\Payment;

The namespace doesn't reflect the entire directory path, so you don't need to include \app. You've already added "MyApp": "app/" to the PSR-0 rules to map that.

Upvotes: 2

Related Questions