Home > Blockchain >  How can I fix the namespace error when using classes within the app folder?
How can I fix the namespace error when using classes within the app folder?

Time:03-09

I am upgrading a legacy laravel application from Laravel 5 to 8 and ran into a brick wall. None of my service providers work, and I cannot figure out why.

Previous Structure

app -->Services ------>Stripe

Within each service provider folder, I'd create three files like so:

  1. Stripe.php
  2. StripeFacade.php
  3. StripeServiceProvider.php

within stripe.php

<?php

namespace app\Services\Stripe;


class Stripe
{

}

?>

within StripeFacade.php

<?php

namespace app\Services\Stripe;

use Illuminate\Support\Facades\Facade;

class StripeFacade extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'Stripe';
    }
}

within StripeServiceProvider.php

<?php

namespace app\Services\Stripe;

use Illuminate\Support\ServiceProvider;

class StripeServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('Stripe', function($app) {
            return new Stripe();
        });
    }
}

in my Config/app.php file, I'd register the service provider and facade like so:

'providers' => [
    app\Services\Stripe\StripeServiceProvider::class,
],

'aliases' => [
    'Stripe' => app\Services\Stripe\StripeFacade::class,
]

In my controller, I'd call the Stripe service as

use Stripe;

...

public function example(){
   $auth = Stripe::auth();
}

Then I'd get this error in the Config/app.php file

Class "app\Services\Stripe\StripeServiceProvider" not found

I tried adding the Services directory to my psr-4 and didn't seem to get any luck even after dumping congifs and autoload.

"autoload": {
        "psr-4": {
            "App\\": "app/",
            "Services\\": "app/Services",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },

any help? :)

CodePudding user response:

In your comment, you posted an error:

Class App\Services\Stripe\StripeServiceProvider located in ./app/Services /Stripe/StripeServiceProvider.php does not comply with psr-4 autoloading standard. Skipping.

I noticed an extra space in ./app/Services /Stripe.

Perhaps you have created the Services / directory with a space at the end.

Some improvements are to rename app\ to App\ and remove the "Services\\": line from your composer.json. Run composer dump-autoload after these changes.

CodePudding user response:

Use the below code

 namespace App\Services\Stripe;

 use App\Services\Stripe\StripeServiceProvider::class
  • Related