Doug Wilbourne
Doug Wilbourne

Reputation: 153

php constructors dependency injection configuration state management

In order to facilitate dependency injection, my php constructors often use only (the dependency) objects as parameters.

On the other hand, the resulting constructed object may not yet be in a valid state - it may need additional configuration before it is in a valid state and ready to use.

Often I will put in a generic method called initialize with whatever parameters are necessary to initialize the object so that it is ready to use.

My question is should one trap for errors/exceptions where a method in the resulting object is called without the object having been initialized, or is it better to simply let another programmer using the object crash and burn if he / she forgets to initialize the object prior to use?

Is there a standard for "being defensive"? Is the answer impacted by whether there are many other methods in the class, which means a lot of repetitious "if not initialized" checks?

Here is some example code:

<?php

class A {}

class B {}

class C 
{
    int $z;

    public function construct(protected A $a, protected B $b) {}

    public function isInitialized(): bool { return isset($this->z); }
     
    public function initialize(int $z) { $this->z = $z; }

    /** crashes and burns if object is not initialized */
    public function otherMethod(): int { return $z; }

    /** trap and throw a custom exception */
    public method anotherMethod(): int
    {
        if (!$this->isInitialized()) throw new Exception;
        return $this->z;
    }

}

Upvotes: 0

Views: 45

Answers (0)

Related Questions