简体   繁体   中英

Type hinting in interfaces

I want to do repositories interfaces. At the moment I have two entities: User and Payment . So I want to do repositories for these entities: UsersRepository and PaymentsRepository .

Every repository in project will have a common abilities, for example: findOne , find , save , delete . So I think I should create a common repository with which other repositories will be extended RepositoryInterface .

<?php
interface UsersRepository extends RepositoryInterface {}

My services will depend on these interfaces. So how I can type-hint, that UsersRepository::findOne will return User entity?

You can specify the return type of the function like this:

<?php
interface UsersRepository extends RepositoryInterface {
    function findOne() : User;
}

Since generics are not available in php you wouldn't be able to do:

<?php
 interface RepositoryInterface<T> {
    function findOne() : T;
    function save(T record);
 }

 interface UsersRepository extends RepositoryInterface<User> {
    function findOne() : User;
 }

So you'll just have to specify the return type for each method in each repo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM