laravel 如何将自定义请求传入Interface类?

gr8qqesn  于 2023-05-30  发布在  其他
关注(0)|答案(1)|浏览(234)

Making Interface class for Crud operations I need in some cases to pass custom requests in app/Repositories/Interfaces/CrudInterface.php我有:

<?php

use Illuminate\Foundation\Http\FormRequest;

interface CrudInterface
{
    public function store(array $data, FormRequest $request): Model;
    ...

但是在实现这个类app/Repositories/TagCrudRepository.php时,我传递CreateTagRequest作为参数:

<?php
namespace App\Repositories;

use App\Http\Requests\CreateTagRequest;

use App\Repositories\Interfaces\CrudInterface;
use Illuminate\Database\Eloquent\Model;
...
use App\Library\TagsSearchResultsIterator;

class TagCrudRepository implements CrudInterface
{

    public function store(array $data, CreateTagRequest $request): Tag
    {
        ...

我得到错误:

Declaration of App\Repositories\TagCrudRepository::store(array $data, App\Http\Requests\CreateTagRequest $request): App\Models\Tag must be compatible with App\Repositories\Interfaces\CrudInterface::store(array $data, Illuminate\Foundat
  ion\Http\FormRequest $request): Illuminate\Database\Eloquent\Model

class app/Http/Requests/CreateTagRequest.php extends extends FormRequest class:

namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;

class CreateTagRequest extends FormRequest
{

如何修复此错误?

kq4fsx7k

kq4fsx7k1#

您可以在运行时传递CreateTagRequesta的示例,但没有任何问题,因为它扩展了FormRequest,但方法签名必须匹配接口(合约)定义的内容。如果需要确保这个特定的store()实现获取的是CreateTagRequest而不是FormRequest的示例,那么需要更改接口或创建另一个方法。没有别的办法了

相关问题