Laravel 仓库模式

一、建立文件夹 

     ●app

         ●Repositories

                ●Interfaces

                ●Repositories

二、创建接口

在interfaces目录下创建文件PostInterface.php

<?php

namesapce  App\Repositories\Interfaces;

Interface PostInterface{

    public function postAll();

}

三、创建实现

在Repositories目录下创建文件PostRepository.php

<?php

namesapce App\Repositories\Repositories;

use App\ Repositories\Interface\PostInterface;

use App\Models\Post;

class PostRepository Implements PostInterface{

    public function postAll()

    {

        $query = Post::all();

        return $query;

    }

四、绑定服务

1.创建RepositoryServiceProvider.php

php artisan make:provider RepositoryServiceProvider

2.打开app/Providers/AppServiceProvider, 在register() 加入代码:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider

{

    public function boot()

    {

    }

     public function register()

    {

         $this->app->bind('App\Repositories\Interfaces\PostInterface', 'App\Repositories\Implements\PostRepository');

    }

}

五、测试仓库

回到PostController;

<?php

namespace app\Http\Controllers\PostController;

use App\Repositories\Interfaces\PostInterface;

class PostController extend Controller{

    protected $postRepo;

    public function __construct(PostInterface $postRepo)

    {

        $this->postRepo = $postRepo;

    }

    public function index()

    {

        $this->postRepo->postAll();

    }

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 3,424评论 0赞 3
  • Laravel框架一:原理机制篇 Laravel作为在国内国外都颇为流行的PHP框架,风格优雅,其拥有自己的一些特...
    Mr_Z_Heng阅读 3,993评论 0赞 13
  • 先说几句废话,调和气氛。事情的起由来自客户需求频繁变更,伟大的师傅决定横刀立马的改革使用新的框架(created ...
    wsdadan阅读 3,244评论 0赞 12
  • 翻阅中外画坛大师们的作品,印象最深的莫过于凡高的《向日葵》了。它没有复杂的勾画,仅用很平淡的语言在倾诉大师对生命的...
    青苇暖阳阅读 370评论 0赞 3
  • (唯品会二面的时候遇到的一个问题因为之前接触的都是可以开出整数的运算,所以就卡壳了。)二分法:
    analanxingde阅读 334评论 0赞 0

友情链接更多精彩内容