I have a project in plain PHP and there is a class which is dependent on external library.
I don’t feel like passing it to constructor everywhere is a good idea (it’s called mainly in tests, but the users of the package will have to pass it to constructor).
I don’t have any DI containers and don’t think I should have because the project is a small package and will only have a few classes.
So I’ve come up with this approach and was wondering if there any consequences or drawbacks of this approach or if there any other solution to this?
protected $client; /** * @param Client|null $client */ public function __construct(Client $client = null) { $this->client = $client ?? new Client(); }
Advertisement
Answer
I don’t see any major issue with that. Your class simply falls back to a default Client
implementation if one isn’t injected into it, but since you’re not enforcing it, it retains the appropriate flexibility/testability.
I would however go a bit further and implement Dependency Inversion:
interface IClient // maybe find a slightly more suitable name for it { // define Client's public interface methods here }
Change your Client class to implement it:
class Client implements IClient { // ... }
Then change the constructor to this:
public function __construct(IClient $client = null) { $this->client = $client ?? new Client(); }
This way your class doesn’t even depend on any implementation at all. It just happens to default to Client
if it isn’t explicitly given one.