嵌套资源-控制器-最佳方法?

时间:2018-08-11 13:23:56

标签: laravel laravel-5.6 controllers laravel-controller

我目前正在构建一个应用程序,其中有多个具有“具有联系”功能的模型,并且想知道如何在控制器中以最佳方式处理该问题。

我在下面列出了一些方法-你们认为哪种方法最好,为什么?或者您个人使用的方法,为什么?

方法1-嵌套资源控制器

namespace App\Http\Controllers;

class SupplierContactController extends Controller
{
    public function all(Supplier $supplier)
    {
        return response($supplier->contacts);
    }

    public function store(Request $request, Supplier $supplier)
    {
        $supplier->contact($request->user()->id, $request->all());

        return response(null, 201);
    }
}

方法2-嵌套资源控制器,扩展了另一个父资源控制器

namespace App\Http\Controllers;

class SupplierContactController extends ContactController
{
    public function all(Supplier $supplier)
    {
        return parent::all($supplier);
    }

    public function store(Request $request, Supplier $supplier)
    {
        return parent::store($request, $supplier);
    }
}

方法3-每种模型类型都有方法的资源控制器

namespace App\Http\Controllers;

class ContactController extends Controller
{
    public function forSupplier(Supplier $supplier)
    {
        return $this->forModel($supplier);
    }

    public function forCustomer(Customer $customer)
    {
        return $this->forModel($customer);
    }

    public function storeForSupplier(StoreContact $request, Supplier $supplier)
    {
        return $this->store($request, $supplier);
    }

    public function storeForCustomer(StoreContact $request, Customer $customer)
    {
        return $this->store($request, $customer);
    }

    private function forModel(Model $model)
    {
        return response($model->contacts);
    }

    private function store(Request $request, Model $model)
    {
        $model->contact($request->user()->id, $request->all());

        return response(null, 201);
    }
}

方法4-具有路由参数和if语句的资源控制器

namespace App\Http\Controllers;

class ContactController extends Controller
{
    public function all(string $type, int $id)
    {
        if ($type === 'supplier') $model = Supplier::find($id);
        if ($type === 'customer') $model = Customer::find($id);

        return response($model->contacts);
    }

    public function store(Request $request, string $type, int $id)
    {
        if ($type === 'supplier') $model = Supplier::find($id);
        if ($type === 'customer') $model = Customer::find($id);

        $model->contact($request->user()->id, $request->all());

        return response(null, 201);
    }
}

0 个答案:

没有答案