DIY implementation of ThinkPHP core framework (14)

Time:2021-1-18

Dependency injection is automatically completed by the container. With reflection mechanism, independent dependency injection can be realized. modifyRrequestClass is constructed as follows

namespace think;

class Request
{
    public function __construct(App $app, $name)
    {
        var_dump($app instanceof App, $name);
    }
}

At the same timebindParams()Method, withgetClass()Method to get the parameter type promptgetName()Method to get the class name of the created instance.

protected function bindParams(ReflectionFunctionAbstract $reflect, array $vars = []): array
    {
        //If the class has no configuration parameters, it returns an empty array directly
        if ($reflect->getNumberOfParameters() == 0) {
            return [];
        }
        $args   = [];
        //Get parameter information
        $params = $reflect->getParameters();

        foreach ($params as $param) {
            $name = $param->getName();
            $class = $param->getClass();
            if (isset($vars[$name])) {
                $args[] = $vars[$name];
                //If no parameters are passed, the default parameters are used
            } elseif ($param->isDefaultValueAvailable()) {
                $args[] = $param->getDefaultValue();
            //If the parameter type is obtained, further instantiation is implemented
            } elseif ($class) {
                $args[] = $this->make($class->getName());
            }
        }

visitdiy.tp, successfully printed out

bool(true) string(4) "five"

It indicates that the dependency injection is realized successfully by reflection, and then it is deletedRequestClass for future demonstration.

This work adoptsCC agreementReprint must indicate the author and the link of this article