D
D
dev4002016-10-28 09:33:11
PHP
dev400, 2016-10-28 09:33:11

What if you need to call the parent constructor with dependencies?

Suppose there is a handler, and every class of a certain type needs it (all subtypes also need this handler).

<?php

interface SomeHandlerInterface {

    public function checkParam( string $userName ) : string;

}


class SomeHandler implements SomeHandlerInterface{

    /**
     * @param string $userName
     * @return string
     * The method does something with the user name
     */
    public function checkParam( string $userName ) : string {

        return $userName;

    }

}

I would like to declare it in the parent class, and pull it in the heirs
class ParentClass {

    /**
     * @var SomeHandler
     */
    protected $someHandler;

    public function __construct(SomeHandlerInterface $someHandler) {

        $this->someHandler = $someHandler;

    }

}

but then we force ourselves to do so
class ChildClass extends ParentClass{


    public function __construct() {

        parent::__construct( new SomeHandler() );

    }

}

and kill di. How can you get out of this situation? It is somehow expensive to transfer the dependency to each subtype, for example, you can pull out the arguments of the parent by reflection, or else how to cheat. What are the options?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
OnYourLips, 2016-10-28
@dev400

class ChildClass extends ParentClass {
    public function __construct(
        SomeHandlerInterface $someHandler,
        AnotherHandlerInterface $anotherHandler
    ) {
        parent::__construct($someHandler);
        $this->anotherHandler = $anotherHandler;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question