I am trying to build a PHP application using the Repository Pattern but I'm not sure how I should implement the save
method.
I have an abstract class called ItemRepository
which have the following method:
abstract class ItemRepository
{
public function save(Item $item);
}
Where Item
also is an abstract class.
Now I want to implement the class MovieRepository
which extends ItemRepository
. Here I want to save instances of the Movie
class which extends Item
.
Though doing it like this in PHP
// MovieRepository.php
class MovieRepository extends ItemRepository
{
public function save(Movie $movie)
{
...
}
}
gives the following error
Declaration of MovieRepository::save() should be compatible with ItemRepository::save(Item $item)
What is the right way to do this?
Best Answer
Drop the Item/Movie types from the save() method:
PHP is primarily dynamically typed language and while I understand the desire to use types as much as possible, in this case PHP's type system is not strong enough to express what you need. In other languages (Java, C++), you could express it with generics, which PHP lacks.