Constract 契约自定义
契约自定义使用
- 在 app 目录下新建 Constracts 目录
- 在 app/Constracts 目录下新建 TestConstract
<?php
namespace App\Contracts;
interface TestContract
{
public function callMe($controller);
}
- 在 app/Services 目录下创建 TestService
<?php
namespace App\Services;
use App\Contracts\TestContract;
class TestService implements TestContract
{
public function callMe($controller)
{
dd('Call Me From TestServiceProvider In '.$controller);
}
}
- 生成服务提供者
php artisan make:provider TestServiceProvider
- 在 TestServiceProvider 的 boot 方法中注册实现类
public function boot()
{
//使用bind绑定实例到接口以便依赖注入
$this->app->bind('App\Contracts\TestContract',function(){
return new TestService();
});
}
- 在 app/config/app.php 中添加服务提供者配置
'providers' => [
...
\App\Providers\TestServiceProvider::class,
...
]
- 在控制器中使用
use App\Contracts\TestContract;
class TestController extends Controller
{
protected $contract;
public function __construct(TestContract $contract)
{
$this->contract = $contract;
}
public function index(Request $request){
$this->contract->callMe('123');
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: