英文:
How to pass custom requests into Interface class?
问题
在app/Repositories/TagCrudRepository.php
中,将CreateTagRequest
的类型提示更改为FormRequest
,以与CrudInterface
中的类型提示保持一致。如下所示:
public function store(array $data, FormRequest $request): Tag
{
// ...
}
这将解决错误,使TagCrudRepository
中的store
方法与CrudInterface
中的方法兼容。
英文:
Making Interface class for Crud operations I need in some cases to pass custom requests
in app/Repositories/Interfaces/CrudInterface.php I have :
<?php
use Illuminate\Foundation\Http\FormRequest;
interface CrudInterface
{
public function store(array $data, FormRequest $request): Model;
...
But when in implementation of this class app/Repositories/TagCrudRepository.php I pass CreateTagRequest as parameter :
<?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
{
...
I got error :
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
{
How this error can be fixed ?
答案1
得分: 2
Tag FormRequest
需要匹配接口定义的方法签名,以确保 store()
方法接收 CreateTagRequest
实例而不是 FormRequest
实例。如需实现此目的,你可以更改接口或创建另一个方法。别无他法。
英文:
You can pass instance of CreateTagRequesta
at runtime w/o any problems though because it extends FormRequest
but method signature must match what interface (contract) defines. If you need to ensure that this particular store()
implementation gets instance of CreateTagRequest
and not FormRequest
, then you either need to change the interface or create another method. There's no other way.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论