找不到 PHP 自动加载类


PHP autoloading class not found

让我先解释一下我为达到这一点做了什么。github上有一个名为no-framework的教程,这是 https://github.com/PatrickLouys/no-framework-tutorial 非常好的教程!我已经完成了它,现在想添加更多库。我有自动加载的作曲家设置,文件看起来像这样。

{
"name": "xxx/no-framework",
"description": "no framework",
"authors": [
    {
        "name": "xxx",
        "email": "xxx@gmail.com"
    }
],
"require": {
    "php": ">=5.5.0",
    "filp/whoops": ">=1.1.2",
    "patricklouys/http": ">=1.1.0",
    "nikic/fast-route": "^0.7.0",
    "rdlowrey/auryn": "^1.1",
    "twig/twig": "~1.0",
    "illuminate/database": "*"
},
"autoload": {
    "psr-4": {
        "App''": "src/"
    }
}

}

在我的src文件夹中,我创建了一个名为Models的文件夹,其中有一个Books.php,在Books.php中我有这个

<?php
    class Book extends 'Illuminate'Database'Eloquent'Model{
        protected $table = 'books';
    }

在我的Bootstrap.php文件中,我在需要作曲家自动加载器后包含了这一行

include('Database.php');

Database.php文件也在src中,如下所示

<?php
    use 'Illuminate'Database'Capsule'Manager as Capsule;  
    $capsule = new Capsule; 
    $capsule->addConnection(array(
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'test',
        'username'  => 'test',
        'password'  => 'l4m3p455w0rd!',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => ''
    ));
    $capsule->bootEloquent();

现在是错误。当我尝试通过尝试将其use到我的一个控制器中来使用它来Book类时

<?php
    namespace App'Controllers;
    use Http'Request;
    use Http'Response;
    use App'Template'Renderer;
    use App'Models'Book as Book;

    class Pages{
       private $request;
       private $response;
       private $renderer;
       public function __construct(Request $request, Response $response, Renderer $renderer){
           $this->request = $request;
           $this->response = $response;
           $this->renderer = $renderer;
       }
       public function index(){
          $book = new Book;
          $book->title = 'test';
          $book->save();
          $html = $this->renderer->render('index');
          $this->response->setContent($html);
      }
  }

收到一个错误,说"找不到类'应用程序''模型''书'"我假设我没有正确自动加载某些内容,但别名的东西在composer.json中,或者可能是其他问题 idk。 帮助?本教程使用一个名为 Auryn 的依赖注入器库,也许我在那里缺少一些东西?不过,IDK对此表示怀疑。

编辑:如果我将use语句更改为这样的include include('../src/Models/Book.php');并像这样在类实例化前面放一个' $book = new 'Book;然后它有效,但这显然不是正确的方法。

我相信 Composer 类映射只是告诉系统在哪里可以找到给定类的文件.PHP仍然需要知道命名空间。 Pages位于App'Controllers命名空间中。 Book没有给出一个,所以它将存在于 'Book 的全局命名空间中。您的Books.php(文件名通常与它们包含的类匹配,因此Book.php)应包含命名空间声明。我建议namepsace App'Models;.您也可以将use语句更改为 use 'Book

请注意,您不需要为其设置别名。它是您正在使用的唯一Book类,因此就像您对类所做的Request一样,该类可以通过其完全命名空间指定的最后一段引用。