首页 > 解决方案 > 流明定制服务商

问题描述

我是 Lumen 的新手,并且进行了全新安装(v8.2.4)并遵循文档,尝试编写自己的服务,但我不断收到错误消息

 "Target class [App\Prodivers\BatmanServiceProvider] does not exist."

就像我说的,根据 Lumen 文档,它是全新安装的。

在 /bootstrap/app.php

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

在 /app/Providers/BatmanServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class BatmanServiceProvider extends ServiceProvider
{

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

我的控制器: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!";
    }


}

我错过了什么/做错了什么?

标签: phplaravellumen

解决方案


  1. 在 /bootstrap/app.php
    $app->register(App\Providers\BatmanServiceProvider::class);
  1. 在 /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. 在 your_lumen_project/app 中创建 Services 文件夹,并创建 php 文件 BatmanService.php

在 /app/Services/BatmanService.php

<?php

namespace App\Services;

class BatmanService
{
    public function sayHello(){
        return 'hi, space!';
    }
}
  1. 现在,您可以在任何地方使用!
<?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!"
    }


}

推荐阅读