【问题标题】:Design pattern to reuse code with different instances使用不同实例重用代码的设计模式
【发布时间】:2014-11-25 05:31:43
【问题描述】:

我正在开发一个 API,并且在控制器中,indexstoreshowupdatedestroy 方法都相同,除了正在使用的模型。

您将如何实现这一点?

我正在考虑使用ActionRepository 创建这些方法并以某种方式解析模型。不过,我不确定如何才能达到模型..

非常感谢您对此的反馈;)!

【问题讨论】:

  • BaseController 的方法,以及注入到扩展它的控制器的模型/存储库 - 我的头顶。
  • 它是一个抽象类还是你的意思,你能提供一个简单的例子吗?将不胜感激:)! @JarekTkaczyk

标签: php design-patterns laravel design-principles laravel-5


【解决方案1】:

你可以这样做:

abstract class BaseController extends LaravelController {
  protected $repository; // or $model or whatever you need

  public function index() { // your logic }
  public function show($id) {
    // your logic here, for example
    return $this->repository->find($id);
    // or
    return $this->model->find($id);
  }
  public function create() { // your logic }
  public function store() { // your logic }
  public function edit($id) { // your logic }
  public function update($id) { // your logic }
  public function destroy($id) { // your logic }
}

class SomeSolidController extends BaseController {
  public function __construct(SomeRepositoryInterface $repository)
  {
    $this->repository = $repository;
  }
}

【讨论】:

  • 我将如何在 Laravel 5 中使用 Request 类?因为在每种方法中我都必须注入另一个 Request 对象。例如,来自Eventcontroller,我的Basecontroller 中的更新方法需要UpdateEventRequest
  • 然后调整它,我展示的方式是用于基本的 L4 控制器。在 Laravel5 中,由于方法注入和其他很酷的功能,您拥有更多功能。
  • 关于如何将特定 Request 类注入 BaseController 方法的任何建议或提示?
猜你喜欢
  • 1970-01-01
  • 2013-06-23
  • 2011-08-09
  • 1970-01-01
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多