class not found:递归反射以注入依赖

时间:2017-04-09 04:50:53

标签: php dependency-injection composer-php autoload psr-4

我试图理解php中mvc架构的一些高级概念,比如使用psr-4和依赖注入容器自动加载。我使用composer autoload创建了一个依赖注入容器和加载类。 每当我运行此代码时,我都会收到以下错误:

  

致命错误:带有消息的未捕获异常'ReflectionException'   '等级测试不存在'   C:\ xampp \ htdocs \ practice \ reflection \ Container \ Container.php:15 Stack   追踪:#0   C:\ XAMPP \ htdocs中\实践\反射\集装箱\ Container.php(15):   ReflectionClass-> __ construct('Test')#1   C:\ XAMPP \ htdocs中\实践\反射\的index.php(9):   Container \ Container :: newInstanceOf('Test')#2 {main}引入   C:\ XAMPP \ htdocs中\实践\反射\集装箱\ Container.php

看起来像Container.php没有从控制器目录中获取类。我找不到这个问题背后的原因。

我的目录结构如下:

-reflection Directory
  -Controller folder
    -Test.php
    -Test2.php
  -Container Directory
    -Container.php
-vendor Directory
-index.php

的index.php:

require 'vendor/autoload.php';

use Container\Container;
use Controller\Test;
use Controller\Test2;

$test = Container::newInstanceOf('Test');

$test->testHi();

Container.php:

namespace Container;

class Container
{

     public static function newInstanceOf($class)
     {

         $reflection = new \ReflectionClass($class);

         $constructor = $reflection->getConstructor();

         if ( ! $constructor)
         {

             return new $class;

         }
         $params = $constructor->getParameters();

         if (count($params) === 0)
         {

             return new $class;

         }

         $newInstanceParams = [];

         foreach($params as $param)
         {
             if(is_null($param->getClass()))
             {
                 $newInstanceParam[] = null;

                 continue;
             }

             $newInstanceParams[] = self::newInstanceOf($param->getClass()->getName());

         }

         return $reflection->newInstanceArgs($newInstanceParams);

     }

}

Test.php:

namespace Controller;

class Test
{

    private $test2;

    public function __construct(Test2 $test2)
    {

        $this->test2 = $test2;

    }
    public function testHi()
    {
        $this->test2->test2Hi();

    }


}

Test2.php:

namespace Controller;

class Test2
{

    public function __construct()
    {

    }

    public function test2Hi()
    {
       echo 'hi from test 2 !';
    }
}

Composer.json:

{
    "autoload":{

            "psr-4":{
                     "Controller\\" : "Controller",
                     "Container\\"  : "Container"

            }

    }

}

1 个答案:

答案 0 :(得分:1)

更改行:

$test = Container::newInstanceOf('Test');

到:

$test = Container::newInstanceOf('Controller\Test');