4

I have inherited some code like this

    public static function instanciateRepository( $repositoryClass, ... ) {
...
        new $repositoryClass( ... );
    }

Where $repositoryClass is a class type that needs to be instanciated.

I want to add a syntax check for passing a wrong class argument to this function, specifically limit $repositoryClass to sublasses of CommonRepository. Is there a syntax construction to achieve that in PHP, e.g. instanciateRepository( CommonRepository::class $repositoryClass, ..?

Anton Duzenko
  • 2,366
  • 1
  • 21
  • 26
  • 1
    Which version are you using? You can simply restrict parameter type like this: `import CommonRepository // import from specific location.` and next `public static function instanciateRepository( CommonRepository $repositoryClass, ... )` – Oliwer Lisek Oct 03 '22 at 10:50
  • That would mean the parameter is instance of a class, while I need to pass a class type here. @OliwerLisek PHP version is 7.4 – Anton Duzenko Oct 03 '22 at 12:18
  • Why you need literally inject a class, not an instance of class? What are you trying to do? – Oliwer Lisek Oct 03 '22 at 20:14
  • @OliwerLisek The legacy code uses it to instantiate a new instance of that class. – Anton Duzenko Oct 04 '22 at 07:50
  • It would help if you were a bit more clear about exactly what `$repositoryClass` argument is and what you are trying to do with it. But you can use [instanceof](https://www.php.net/instanceof) to check if your instantiated class conforms to a particular type. https://stackoverflow.com/a/1965730/11061164 – mark_b Oct 04 '22 at 09:02
  • @mark_b that will be already too late. I want this check to happen statically in IDE – Anton Duzenko Oct 05 '22 at 10:42

1 Answers1

0

Start off with an interface that defines the common methods

interface CommonRepositoryInterface {}

Your CommonRepository class should be an abstract class that implements the interface and common methods

abstract class CommonRepository implements CommonRepositoryInterface {}

Now your repository classes can extend the CommonRepository but still implement the interface

final class RepositoryClass extends CommonRepository {}

Finally your function can take the interface as an argument so that any class instantiations passed in must be of that type

public static function instanciateRepository(CommonRepositoryInterface $repositoryClass, ... ) {}
mark_b
  • 1,393
  • 10
  • 18