Question

I am trying to use DI to put one object into another. This is easy using an interface and type hinting.

The problem is that the object I am injecting returns another object with one of the expected methods, and this object cannot be type hinted. The problem looks something like this.

class Db implements DbInterface {
    public function query($query) {
        return new Result($query);
    }
}

interface DbInterface {
    public function query($query);
}

class Result {
    public function getRow() {
        // get row here
    }
}

class SomeClass {
    protected $data;

    // injection is here
    public function __construct(DbInterface $db) {
        $result = $db->query($some_query);
        $this->data = $result->getRow();
    }
}

I can make sure I get the right DbInterface object, but is there no way to make sure that this object's run() method returns the right kind of object? I have looked, and cannot find a way to type hint a function's return result.

This could lead to problems later on in more complex code. If someone writes a new implementation of the DbInterface, how will they know that run needs to return a specific type of object if there is no way to enforce it?

Was it helpful?

Solution

put the whole thing under test. if one of your tests specifies that the return type must be x, hopefully the test would fail when using the new implementation. beyond the test failing, hopefully the developers would use the tests as developer documentation and see what the intended behavior is.

OTHER TIPS

No, on the language level it's not possible to constrain a function's return value. Only the function arguments' type hints are allowed — http://www.php.net/manual/en/language.oop5.typehinting.php

What you could do, is making sure that the wrong type of the returned value is caught early. Say, in the IOC container startup code. You instantiate your DbInterface, and check the return type of run(). If it's wrong, throw an exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top