简体   繁体   English

我无法使用psr-4自动加载课程

[英]I cannot autoload my class using psr-4

I am learning auto loading my calss using psr-4 but I have no luck,here is my folder structure 我正在学习使用psr-4自动加载Calss,但没有运气,这是我的文件夹结构

在此处输入图片说明

Here is the code inside my "Employee.php" 这是我的“ Employee.php”中的代码

   namespace app\Employee;


class Employee
{
   public function __construct(){
       echo "hello employee";

   }

}

and in my index.php 在我的index.php中

use app\Employee;


  $emp = new Employee;

Here is my composer.json 这是我的composer.json

{
  "autoload": {
    "psr-4": {
       "Employee\\":"app/Employee"
    }
  }
}

Your current autoloader, expects that the "Employee" namespace is mapped within the "app/Employee/" directory. 您当前的自动装带器希望将“ Employee”命名空间映射到“ app / Employee /”目录中。

With your setup, you would need to add in index.php 安装完成后,您需要添加index.php

use Employee\Employee;

$emp = new Employee();

And the actual namespace of Employee.php would be: Employee.php的实际名称空间将是:

namespace Employee;

class Employee {}

Change 更改

use app\Employee;

$emp = new Employee;

to: 至:

use Employee\Employee;

$emp = new Employee();

From your code in Employee.php : 从您在Employee.php的代码:

namespace app\Employee;

This is the namespace you have to use if you want to access the class. 这是您要访问类时必须使用的名称空间。

PSR-4 in Composer works like this: Composer中的PSR-4的工作方式如下:

"autoload":{"psr-4": { "Namespace\Prefix":"a/path"}}

When loading a class "Namespace\\Prefix\\Class", Composer will see the PSR-4 entry and compare if the class being loaded starts with that Prefix. 加载类“名称空间\\前缀\\类”时,Composer将看到PSR-4条目,并比较所加载的类是否以该前缀开头。 It does! 是的! Now it remove the detected prefix from the classname, and treats the rest as a path and file name relative to "a/path". 现在,它从类名中删除检测到的前缀,并将其余部分视为相对于“ a / path”的路径和文件名。

So the remainder of that class is "Class", and because there is no backslash left, this directly is the filename "Class.php" (note the uppercase filename). 因此,该类的其余部分为“ Class”,并且由于没有反斜杠,因此直接使用文件名“ Class.php”(请注意大写的文件名)。 This file is searched in "a/path/Class.php". 在“ a / path / Class.php”中搜索该文件。

For your situation, you almost did everything right - the only thing: Your namespace prefix in composer.json is not Employee\\ - you gave the correct prefix in your code above. 对于您的情况,您几乎做对了所有事情-唯一的事情: composer.json名称空间前缀不是Employee\\ -您在上面的代码中提供了正确的前缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM