I would like to combine 2 objects through composition with one optional object and keep a generic and clean API. To provide an example:
class Composition implements Object1Interface, Object2Interface
{
    private $object1;
    private $object2;
    public function __construct($object1, $object2 = null)
    {
        $this->$object1 = $object1;
        $this->$object2 = $object2;
    }
    // This will always work since the object is mandatory.
    public function getId() {
        return $this->object1->getId();
    }
    // This may fail because the object2 can be null.
    public function getName() {
        return $this->object2->getName();
    }
}
You could see that this starts to fail pretty fast since I could be proxying on a null object here. What would be a good way to solve this?
If I were to make $object2 mandatory while I might not have all the constructor data at all times to fill out $object2, I need to make all arguments for the constructor optional. This seems like a big no-no since it would no longer have required arguments.
An option would be to create a method to return $object2 but this requires chaining by a user like so:
$composition->getObject2()->getName()
This could be acceptable but I am destroying the clean API that I have and am now chaining methods.
Is there anything that can be done here to fix this or should I simply go with the mentioned chaining of methods solution?
 
     
    