Laravel 4使用IoC容器设置模型

ehp*_*ehp 1 php laravel laravel-4

我最近看了这个视频,想要改变我的Laravel控制器,以便他们用Laravel的IoC容器管理它们的依赖.该视频讨论了为Model创建接口,然后为所使用的特定数据源实现该接口.

我的问题是:当实现具有扩展Eloquent的类并将该类绑定到控制器以便可以从中访问的$this->model接口时,我是否还应该为Eloquent模型创建接口和实现,这些接口和实现可能在调用方法时返回$this->model->find($id)?Model和ModelRepository应该有不同的类吗?

换句话说:new Model当我的模型进入时我该怎么做$this->model.

fid*_*per 9

通常,是的,执行该模式的人(存储库模式)有一个接口,其中定义了一些应用程序将使用的方法:

interface SomethingInterface {

    public function find($id);

    public function all();

    public function paged($offset, $limit);

}
Run Code Online (Sandbox Code Playgroud)

然后你创建一个这样的实现.如果您正在使用Eloquent,那么您可以进行Eloquent实施

use Illuminate\Database\Model;

class EloquentSomething {

    protected $something;

    public function __construct(Model $something)
    {
        $this->something = $something;
    }

    public function find($id)
    {
        return $this->something->find($id);
    }

    public function all() { ... }

    public function paged($offset, $limit) { ... }

}
Run Code Online (Sandbox Code Playgroud)

然后,您将服务提供商放在一起,并将其添加到其中app/config/app.php.

use Something; // Eloquent Model
use Namespace\Path\To\EloquentSomething;
use Illuminate\Support\ServiceProvider;

class RepoServiceProvider extends ServiceProvider {

    public function register()
    {
        $app = $this->app;

        $app->bind('Namespace/Path/To/SomethingInterface', function()
        {
            return new EloquentSomething( new Something );
        });
    }

}
Run Code Online (Sandbox Code Playgroud)

最后,您的控制器可以使用该接口作为类型提示:

use Namespace/Path/To/SomethingInterface;

class SomethingController extends BaseController {

    protected $something;

    public function __construct(SomethingInterface $something)
    {
         $this->something = $something;
    }


    public function home() { return $this->something->paged(0, 10); }

}
Run Code Online (Sandbox Code Playgroud)

那应该是它.对任何错误道歉,这没有经过测试,但我做了很多事情.

缺点:

更多代码:D

上升空间:

  • 能够切换实现(而不是EloquentSomething,可以使用ArraySomething,MongoSomething,等等),而无需更改控制器代码或任何使用接口实现的代码.
  • 可测试 - 您可以模拟您的Eloquent类并测试存储库,或模拟构造函数依赖项并测试您的控制器
  • App::make()重用- 您可以在应用程序中的任何位置获取具体的EloquentSomething,并在代码中的任何位置重新使用Something存储库
  • 存储库是添加其他逻辑的好地方,例如缓存层,甚至是验证规则.股票在你的控制器中乱搞.

最后:因为我可能输入了所有内容而仍然没有回答你的问题(wtf?!),你可以使用获得模型的新实例$this->model.这是创建新东西的示例:

// Interface:
public function create(array $data);

// EloquentSomething:
public function create(array $data) 
{
    $something = this->something->newInstance();
    // Continue on with creation logic
}
Run Code Online (Sandbox Code Playgroud)

关键是这个方法newInstance().