Search code examples
phplaravellumen

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 [App\Prodivers\BatmanServiceProvider] does not exist."

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

in /bootstrap/app.php

$app->register(App\Providers\BatmanServiceProvider::class);

in /app/Providers/BatmanServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class BatmanServiceProvider extends ServiceProvider
{

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

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

<?php

namespace App\Http\Controllers;

use App\Prodivers\BatmanServiceProvider;

class MainController extends Controller{


    public function __construct(BatmanServiceProvider $BatmanServiceProvider){

    }

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


}

What am I missing/doing wrong?


Solution

    1. in /bootstrap/app.php
        $app->register(App\Providers\BatmanServiceProvider::class);
    
    1. in /app/Providers/BatmanServiceProvider.php
    <?php
    
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use App\Services\BatmanService;
    
    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 App\Services;
    
    class BatmanService
    {
        public function sayHello(){
            return 'hi, space!';
        }
    }
    
    1. Now, you can use anywhere!
    <?php
    
    namespace App\Http\Controllers;
    
    use App\Services\BatmanService;
    
    class MainController extends Controller{
    
        protected $batmanService;
        public function __construct(BatmanService $batmanService){
            $this->batmanService = $batmanService;
        }
    
        public function main(){
            return $this->batmanService->sayHello(); // "hi, space!"
        }
    
    
    }