Laravel 服务容器 绑定接口到实现

31. May 2018 Laravel 0

1.在项目根目录app下创建Contract和Services文件,然后编写自己的接口文件(ProductInterface.php)和接口实现文件(ProductService.php)

如接口文件

<?php

namespace App\Contract;

interface ProductInterface
{
public function lists();
public function show(int $service_id);
}

接口实现文件

<?php

namespace App\Services;

use App\Contract\ProductInterface;

class ProductService implements ProductInterface
{
/*
* 产品列表数据service
*/
public function lists()
{
//code here
}

/*
* 产品列表详情service
*/
public function show(int $service_id)
{
//code here
}
}

2.在服务容器中注册

可在app/Providers下AppServiceProvider里register中注册

$this->app->bind('App\Contract\ProductInterface', 'App\Services\ProductService');

3.在控制器中注入使用

<?php

namespace App\Http\Controllers;

use App\Contract\ProductInterface;
use Illuminate\Http\Request;

class ProductController extends Controller
{
private $product;

public function __construct(ProductInterface $product)
{
$this->product = $product;
}

/*
* 产品类别接口,分类别返回所有产品数据
*/
public function lists()
$res = $this->product->lists();
// code here continue
}

4.更新自动加载文件和缓存(若有的话)

composer dump-autoload //很重要
php artisan config:clear
php artisan route:clear