jeudi 23 juillet 2020

Repository pattern: how do I accurate the signature (return type) of a function?

I'm using the repository pattern to fetch my data from the database.

Here is my base class:

class BaseRepository implements EloquentRepositoryInterface
{
 
  protected $model;

  public function __construct(Model $model)
  {
    $this->model = $model;
  }

  
  public function findOrFail($id): Model
  {
    try {
      return $this->model->findOrFail($id);
    } catch (\Exception $e) {
      throw new \Exception($e);
    }
  }

}

which implements this interface:

interface EloquentRepositoryInterface
{
  public function findOrFail($id): Model;
}

Then I have one entity called Item, which extends Model:

class Item extends Model
{
  // ... 
}

And what I want to do is create an ItemRepositoryInterface:

interface ItemRepositoryInterface extends EloquentRepositoryInterface
{
  public function findOrFail($id): Item;
}

But I can't change the interface signature... PhpStorm is telling me that is incompatible so I had to remove the public function findOrFail($id): Item from the interface. So that my $itemRepository->findOrFail() respects the signature of EloquentRepositoryInterface.

Here my ItemRepository :

class ItemRepository extends BaseRepository implements ItemRepositoryInterface
{
   // ...
}

The problem

is that when I use $itemRepository->findOrFail() the specs tells me it's returning a Model

What I want

is that when I call $itemRepository->findOrFail() the specs should tell me that it's returning an Item

Is there a way to have this behaviour ? Like keeping the signature of findOrFail() inside EloquentRepositoryInterface and 'overwrite' the return type of it, without having to rewrite the whole function ?

Aucun commentaire:

Enregistrer un commentaire