第一步:
在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
本文详细介绍了如何在应用程序中实施Repository模式,包括创建Repository文件夹、定义和实现接口类、注册服务提供者以及在控制器和模板中使用这些Repository。通过实际代码示例,读者可以学习如何有效地分离业务逻辑和数据访问层。
271

被折叠的 条评论
为什么被折叠?



