Search code examples
phplaravellaravel-4namespacesservice-provider

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?


Solution

  • 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;