Laravel 仓库模式

2019-02-26  本文已影响0人  hankin_h

一、建立文件夹 

     ●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();

    }

上一篇下一篇

猜你喜欢

热点阅读