Skip to content
Advertisement

Custom service provider for Lumen

I’m new to Lumen, and have a fresh install (v8.2.4) and have followed the docs, trying to write my own service, but I keep getting error

 "Target class [AppProdiversBatmanServiceProvider] does not exist."

Like I said, its a fresh install according to the Lumen docs.

in /bootstrap/app.php

$app->register(AppProvidersBatmanServiceProvider::class);

in /app/Providers/BatmanServiceProvider.php

namespace AppProviders;

use IlluminateSupportServiceProvider;

class BatmanServiceProvider extends ServiceProvider
{

    public function register()
    {
        return "batman!";
    }
}

My controller: app/Http/Controllers/MainController.php

<?php

namespace AppHttpControllers;

use AppProdiversBatmanServiceProvider;

class MainController extends Controller{


    public function __construct(BatmanServiceProvider $BatmanServiceProvider){

    }

    public function main(){
        print "hello space!";
    }


}

What am I missing/doing wrong?

Advertisement

Answer

  1. in /bootstrap/app.php
    $app->register(AppProvidersBatmanServiceProvider::class);
  1. in /app/Providers/BatmanServiceProvider.php
<?php

namespace AppProviders;

use IlluminateSupportServiceProvider;
use AppServicesBatmanService;

class BatmanServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(BatmanService::class, function(){
            return new BatmanService;
        });
    }
}
  1. create Services folder in your_lumen_project/app, and create php file BatmanService.php

in /app/Services/BatmanService.php

<?php

namespace AppServices;

class BatmanService
{
    public function sayHello(){
        return 'hi, space!';
    }
}
  1. Now, you can use anywhere!
<?php

namespace AppHttpControllers;

use AppServicesBatmanService;

class MainController extends Controller{

    protected $batmanService;
    public function __construct(BatmanService $batmanService){
        $this->batmanService = $batmanService;
    }

    public function main(){
        return $this->batmanService->sayHello(); // "hi, space!"
    }


}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement