依赖注入

依赖注入的优势

依赖注入的灵活性在于,new这个类的时候可以传入变量,这个变量的值就很灵活了。 如果hint是一个Interface的话,就更灵活了。

<?php

class IndexController
{
    public function __construct(User $user, Order $order)
    {
        echo 'I am IndexController' . PHP_EOL;
        $user->foo();
        $order->foo();
    }

    public function testAction(Order $order)
    {
        $order->foo();
    }
}

class User
{
    public function foo()
    {
        echo 'i am user foo' . PHP_EOL;
    }
}

class Order
{
    public function foo()
    {
        echo 'i am order foo' . PHP_EOL;
    }
}

function make($className)
{
    $reflector    = new ReflectionClass($className);
    $dependencies = $reflector->getConstructor()->getParameters();

    $results = [];

    foreach ($dependencies as $dependency) {
        $class = $dependency->getClass();
        $results[] = new $class->name;
    }

    return $reflector->newInstanceArgs($results);
}

$instance = make('IndexController');
var_dump($instance);

$action    = 'testAction';
$reflector = new \ReflectionMethod($instance, $action);
$parameters = [];
foreach ($reflector->getParameters() as $key => $parameter) {
    $class = $parameter->getClass();
    $parameters[] = new $class->name;
}

call_user_func_array([$instance, $action], $parameters);