第一步:
在app下建立Repository 文件夹
第二步,创建接口类
第三步:实现定义的接口类
第四步:创建后端服务提供
在Providers 中新建RepositoryServiceProvider.php
在register函数中注册刚才的接口类
<?php
namespace App\Providers;
use App\Repository\MenuRepository;
use App\Repository\RoleRepository;
use App\Repository\RoleRepositoryInterface;
use Illuminate\Support\ServiceProvider;
use App\Repository\MenuRepositoryInterface;
class RepositoryServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(MenuRepositoryInterface::class, MenuRepository::class);
$this->app->bind(RoleRepositoryInterface::class,RoleRepository::class);
}
}
第五步:使用
1 在控制器中依赖注入
protected $menu;
public function __construct(MenuRepositoryInterface $menu)
{
parent::__construct();
$this->menu = $menu;//菜单接口
}
2 在模板中使用
@section('sidebar')
<!--使用服务输出html-->
@inject('menus','App\Repository\MenuRepository')
<div class="left-nav">
<div id="side-nav">
<ul id="nav">
{!! $menus->getMenuList($menus->getTreeData()) !!}
</ul>
</div>
</div>
@show