【问题标题】:Composer autoloading namespace error作曲家自动加载命名空间错误
【发布时间】:2018-05-07 22:46:14
【问题描述】:

我一直在玩 Slim 3 和 Doctrine,但没有取得太大进展,因为我一生都无法弄清楚为什么这不起作用。

项目结构:

-src
  |-App
    |-index.php
    |-Entity
      |-User.php

  |-vendor

composer.json

{
    "require": {
        "slim/slim": "^3.9",
        "doctrine/orm": "v2.5.9"
    },
    "autoload": {
        "psr-0":{
            "App\\": "src/App"
        }
    }
}

index.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use App\Entity\User;

require '../vendor/autoload.php';

$user = new User();

....

但这会导致

Fatal error: Class 'App\Entity\User' not found...

我已经尝试了一些使用 psr-4 的变体,但仍然没有成功,任何帮助将不胜感激。

更新: 用户.php

namespace App\Entity;

use App\Entity;
use Doctrine\ORM\Mapping;

/**
 * @Entity
 * @Table(name="users")
 */
class User
{
    /**
     * @var integer
     *
     * @Id
     * @Column(name="id", type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @Column(type="string", length=64)
     */
    protected $name;

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param int $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }


}

【问题讨论】:

  • 它也应该是psr-4 而不是psr-0。有很大的不同。我还建议在您的作曲家文件中以斜线结尾 src/App,如下所示:src/App/(它可能会以任何一种方式工作,但这是标准)。
  • 你能添加User.php吗?命名空间正确吗?顺便说一句@MagnusEriksson,在实例化第一个类之前必须排除自动加载器。所以使用后位置没问题。用法应该是第一行(在命名空间之后;-))
  • @Demigod - 你对自动装载机的位置是正确的。对于use,它必须 是命名空间之后的第一行。这是常见的做法,并且在大多数代码样式​​中都有意义,但 PHP 不会强制执行它,只要您在尝试使用任何导入的类/函数/常量之前拥有它。
  • 感谢您的回复,我现在在办公室,回家后会用用户内容更新问题。

标签: php namespaces composer-php autoload psr-4


【解决方案1】:

调整您的自动加载配置以使用 PSR-4 自动加载器而不是 PSR-0 自动加载器:

{
    "autoload": {
        "psr-4":{
            "App\\": "src/App/"
        }
    }
}

有关参考,请参阅https://getcomposer.org/doc/04-schema.md#psr-4

【讨论】:

    猜你喜欢
    • 2013-04-08
    • 2013-08-11
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 2016-11-30
    • 2018-08-30
    • 2016-07-08
    • 1970-01-01
    相关资源
    最近更新 更多