【问题标题】:Binding repositories to routes将存储库绑定到路由
【发布时间】:2014-04-06 05:54:19
【问题描述】:

我使用 Repository 模式的方式与 Chris Fidao 在Implementing Laravel 书中使用的模式非常接近。基本上我有实现其接口并注入模型的具体存储库类。

现在我想利用 Laravel 的路由绑定。由于我使用的是存储库,因此我无法将它们直接绑定到模型……对吗?然而我没能做到这一点。

我正在使用服务提供者将我的具体存储库绑定到接口,如下所示:

    $app->bind('App\Repositories\UserInterface', function ($app) {
        return new EloquentUser(new User);
    });

如何将我的路由绑定到存储库接口?看似微不足道,但我有点迷茫……

提前感谢您! :)

【问题讨论】:

  • 为什么要将路由绑定到存储库?路由应该指向一个请求处理程序(或多或少是一个服务),而不是一个旨在将业务与持久性分离的存储库
  • 你找到解决办法了吗?

标签: binding laravel repository-pattern laravel-routing


【解决方案1】:

您可以使用不同的方法将模型传递给表单,而无需将模型绑定到路由,例如,假设您有一个使用 UserController 的路由,这是控制器:

class UserController extends BaseController {
    public function __construct(UserInterface $UserRepo)
    {
        $this->repo = $UserRepo;
    }

    public function edit($id)
    {
        $user = $this->user->find($id);
        return View::make('user.edit')->with('user', $user);
    }
}

user.edit 视图中的表单:

{{ Form::model($user, array('route' => array('user.update', $user->id))) }}

【讨论】:

    【解决方案2】:

    您可以通过以下方式在您的路线中使用 Repo。但是,你真的需要这个吗?

    \\the repo is in the Branches folder
    use App\Repos\Branches\BranchRepository;
    
    Route::get('branches',function(BranchRepository $branchRepo){
        \\using a method of your repo - in this case using getData() method
        return $branchRepo->getData();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-08
      • 2017-06-25
      • 2020-02-20
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 2014-10-28
      • 2017-12-05
      相关资源
      最近更新 更多