契約自定義使用
- 在 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()
{
$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 協議》,轉載必須註明作者和本文連結