1.定义接口TestContract

文件位置:./laravel/app/Contract/TestContract.php

<?php
namespace App\Contract;
interface TestContract
{
public function test($msg='');
}

2.实现接口TestContract

文件位置:./laravel/app/Contract/Test.php

<?php
namespace App\Contract;
class Test implements TestContract
{
public function test($msg=''){
echo 'I am Test~ '.$msg;
}
}
?>

3.创建服务提供者,提供Test服务
文件位置:./laravel/app/Contract/TestServiceProvider

<?php
namespace App\Contract;
use Illuminate\Support\ServiceProvider;
use App\Contract\Test;

class TestServiceProvider extends ServiceProvider
{
public function register(){
// 绑定test与Test类的实例
$this->app->singleton('test', function($app){
return new Test();
});
}
}
?>

4.接下来就是创建TestFacade
文件位置:./laravel/app/Contract/TestFacade.php

<?php
namespace App\Contract;
use Illuminate\Support\Facades\Facade;

class TestFacade extends Facade
{
// 这里的test跟服务提供者TestServiceProvider里面注册的'test'一致
protected static function getFacadeAccessor() { return 'test'; }
}
?>

5.接下来就是配置的阶段了
在Config/app.php里面加入
1.服务提供者
给providers加入我们的TestServiceProvider 
   'providers' => [
       /*
        *  my defined 
        */
       App\Contract\TestServiceProvider::class,
 
   ],
2.在aliases添加别名以供调用
'aliases' => [
       'Test'  => App\Contract\TestFacade::class
   ],
6.添加完成,接下来便可以使用了

<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller;
use Test;
class TestController extends Controller {

public function test(){
Test::test('hello world');
}

}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-03
  • 2022-12-23
  • 2021-07-23
  • 2021-09-07
猜你喜欢
  • 2021-12-24
  • 2022-12-23
  • 2021-07-22
  • 2021-11-26
  • 2021-12-08
  • 2021-05-19
  • 2021-11-19
相关资源
相似解决方案