我有一组包含类(实体)的 PHP 文件。每个类都有相同的命名空间:
// src/App/Entity/Actions.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Actions
*
* @ORM\Entity
*/
class Actions
{
// SOME CODE
我使用 Composer 自动加载包含类的 PHP 文件:
"autoload": { "psr-0": { "App": "src/" } }
在我的 bootstrap.php 文件中,我添加了这一行:
use App\Entity;
所以我想,因为告诉应用程序使用 App\Entity 命名空间,所以我可以像这样调用实体类:
$entity = new Actions();
但是当我尝试这样做时,我收到此错误:
Fatal error: Class 'Actions' not found in C:\wamp64\www\spider\chebi2\inc\orm_tools.php on line 49
如果我这样做:
use App\Entity; use App\Repository;
if (class_exists('Actions')) { dump('exists'); } else { dump('not exists'); }
if (class_exists('\App\Entity\Actions')) { dump('exists'); } else { dump('not exists'); }
这是它输出的内容:
PS C:\wamp64\www\spider\chebi2> php .\get_actions.php
"not exists"
"exists"
所以只有当我提供完整的命名空间时它才能找到类。奇怪的是,当我尝试这样做时:
// Direct path to the Actions.php file
use App\Entity\Actions;
if (class_exists('Actions')) { dump('exists'); }
else { dump('not exists'); }
if (class_exists('\App\Entity\Actions')) { dump('exists'); }
else { dump('not exists'); }
我得到相同的结果:
PS C:\wamp64\www\spider\chebi2> php .\get_actions.php
"not exists"
"exists"
所以现在我更迷茫了。使用有什么意义:
use App\Entity;
如果它实际上并没有使该命名空间中的类直接可用?以及为什么将直接路径分配给类 use App\Entity\Actions;
甚至不工作?我在这里做错了吗?有没有正确的方法来使用我不理解的命名空间?
最佳答案
PSR-0 已弃用,您应该使用 PSR-4
在 PSR-4
composer.json
"autoload": {
"psr-4": {
"App\\": "src/",
}
}
在与 composer.json 相同级别的目录 src/中添加目录
Entity
所以在路径 src/Entity
添加类文件 Actions
namespace App\Entity;
class Actions
{
}
您也可以使用
composer dump-autoload
并检查 vendor/composer/autoload* 字段并查看是否在那里注册了命名空间。关于
class_exists()
它不适用于您需要提供类的全名的短名称或别名。我建议使用 ::class
运营商所以在你的情况下,它将是:<?php
use App\Entity\Actions;
class_exists(Actions::class);
关于PHP - Doctrine - 如何使用单个命名空间自动加载实体类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40819802/