在 Laravel 中使用模型的正确方法是什么?

What is the proper way to use the Model in Laravel?

你能帮我解决这个问题吗?我目前正在自学 Laravel,并且我遵循了 Laracasts 中的教程,这非常棒。在Laravel之前,我在项目中使用CodeIgniter和Opencart,我开始研究Laravel,因为我想学习一个新的框架。

在 CI 和 Opencart 中,您所有的数据库查询都在模型中。但是在 Laravel 你可以在 Controller? 中执行和查询。它是 Laravel 中查询的正确方法吗?

我在控制器中有这样的代码:

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Article;
use Illuminate\Http\Request;

class ArticlesController extends Controller {

    public function index() {

        $articles = Article::all();

        return view('articles.index')->with('articles', $articles);

    }

}

是的,这非常适合小型应用程序。 然而,对于大型应用程序,我建议使用存储库,因为它们将您的模型与控制器分离 - 这使它们更具可读性和可测试性。

您的 ArticlesController 将转换为如下内容:

<?php namespace App\Http\Controllers;

use App\Repositories\Articles\ArticleRepositoryInterface;

class ArticlesController extends Controller {

    private $articles;

    public function __construct(ArticleRepositoryInterface $articles)
    {
        $this->articles = $articles;
    }

    public function index()
    {
        return view('articles.index')
            ->with('articles', $this->articles->all());
    }

}

看看 Laravels Service Container to understand the automatic resolution of the ArticleRepositoryInterface. Laracasts 有一些关于存储库的好视频。

存储库对您来说是一个明智的决定。但是为什么?
基本上,存储库是您的应用程序和存储之间的 'gateway'。
使用存储库,您可以在一个地方找到您的 'database queries'。

大家想想模型文章吧
而不是在您需要使用它的所有时间使用文章的静态实例(Articles::find()Articles::all() 等),只需创建一个文章存储库。
将此回购注入您的控制器(例如),并在您的 ArticleRepository 中使用 'features' storaged。

什么意思?
让我们考虑一个文章存储库。我将在文章模型的应用程序中多次使用什么?我需要 select 全部,select 按 id,插入,更新,删除。基本上就这些'stuffs'。那么,如果我把所有这些东西都放在一个地方呢?

class ArticleRepository {

    public function all(){}
    public function getById($id){}
    public function insert($data){}
    public function update($data){}
    public function delete($id){}

}

将此 ArticleRepository 注入您的控制器。为此,请在此处阅读有关 IoC 容器的文章:http://laravel.com/docs/5.0/container

控制器中的构造将如下所示:

public function __construct(ArticleRepository $articles)
{
    $this->articles = $articles;
}

总而言之,当您需要在控制器中获取所有文章时,只需执行以下操作:

public function index()
{
    $articles = $this->articles->all();
    return View::make('articles.index')->with(['articles' => $articles]);
}

通过这种做法,您将拥有一个干净的应用程序,其中包含可测试的控制器以及漂亮的组织和设计。 ;)

你看,我尽量用说教的方式让你理解这个概念。使用存储库不仅仅是一种方式。所以我在评论中放了链接。并让其他参考也在这里。
相信你很快就会明白的。
学习成功! :)

https://laracasts.com/search?q=repositories&q-where=lessons
http://ryantablada.com/post/the-repository-pattern-in-action
http://culttt.com/2014/03/17/eloquent-tricks-better-repositories/
http://culttt.com/2013/07/15/how-to-structure-testable-controllers-in-laravel-4/