天天看点

Laravel技巧集锦(27):使用Repository分离model、controller

说明:实际开发时,如果控制器中写的代码太多会影响可读性,因此可以将控制器中的代码放入到Repository中,在控制器中调用就可以了。

1、创建Repositories目录,位于app目录下

namespace App\Repositories;

//实际开发中的代码会更多的对数据进行处理

class QuestionRepository
{
    public function update($id){
       return \App\Question::where('id',$id)->update();
    }

    public function create($data){
       return \App\Question::create($data);
    }
}      
class QuestionsController extends Controller
{

    protected $questionRepository;//定义

    public function __construct(QuestionRepository $questionRepository)
    {
        $this->middleware('auth')->except(['index','show']);
        $this->questionRepository = $questionRepository;
    }


    public function store(StoreQuestionRequest $request)
    {
      $data = [
            'title'=>$request->get('title'),
        ];
        $question = $this->questionRepository->create($data);//调用
    }