Laravel 创建工具服务类

https://www.jianshu.com/p/ddb289e81480

https://blog.csdn.net/qq_37500838/article/details/102835146

用途:在一般控制器中调用不需要实例化直接调用,如:

use App\Facades\Common;

Common::test();

echo \Test::test();
app('common')->test();

一、在Services目录下创建CommonService.php

<php

namespace App\Services;

class 
CommonService

{

    //一些公共方法

    public function test(){

        echo __method__; 

    } 

}

二、在Facades目录下创建Common.php

<php

namespace App\Facades;

user Illuminate\Support\Facades\Facade;

class 
Common extends Facade

{

    protected static function getFacadeAccessor()

    {

        return 'common';

    }

}

三、在Providers目录下创建CommonProvider

<php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use App\Services\CommonService;

class CommonProvider extends ServiceProvider

{

    public function boot()

    {

    }

    public function register()

    {

        $this->app->singleton('common', function(){

            return new
CommonService
();

        });

    }

}

四、在config配置文件中打开app.php

'providers' => [

    ......

    App\Providers\CommonProvider::class,

],

'aliases' => [

     'Test' => App\Facades\Common::class,

],

    A+
发布日期:2021年07月24日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: