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
- in /bootstrap/app.php
$app->register(AppProvidersBatmanServiceProvider::class);
- 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; }); } }
- 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!'; } }
- 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!" } }