我有一组包含类(实体)的PHP文件。每个类都有相同的命名空间:PHP - Doctrine - 如何自动加载实体类使用单个命名空间
// src/App/Entity/Actions.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Actions
*
* @ORM\Entity
*/
class Actions
{
// SOME CODE
我自动加载包含与作曲家类的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;
甚至不能正常工作?
我在这里做错了什么?有没有一种正确的方法来使用我不理解的命名空间?
看看'“/vendor/autoload.php”;' – Robert
的autoload.php文件本身只有两个在它的线条,但我检查了vendor/composer/autoload_psr4.php文件,它列出了** composer.json **文件中的所有软件包,但没有列出应该使用psr4自动加载器自动加载的任何文件。在** autoload_namespaces.php **中,它不会列出我添加的任何名称空间。当我运行** composer diagnose **时,其中一行是这样的:'属性psr-4没有被定义,并且定义不允许附加属性' –
所以在读完一些东西之后,似乎我误解了'使用某些\命名空间'命令是做什么的。我认为'使用App \ Entity;'会将该名字空间中每个类的名称加载到全局变量中,但实际上做的是创建为名为Entity的别名。所以相反,我需要像这样调用类\ Entity \ Actions。我不明白它,因为我通过作曲家安装了很多不同的组件,我添加了'use path \ to \ namespace;',然后我可以直接调用这些类。 –