未找到 Composer 自动加载类 [英] Composer Autoloading classes not found
问题描述
我的文件夹结构如下:
includes/
libraries/
Classes/
Contact/
Contact.php
ContactController.php
admin/
controllers/
contact/
edit.php
Contact.php 是我尝试使用的那个文件的类.该文件包含.
Contact.php is my class that file that I'm trying to use. The file contains.
<?php
namespace Classes;
class Contact {
function __construct() {
die('here');
}
}
我的 composer.json 文件如下:
I have my composer.json file like:
{
"autoload": {
"psr-4": {
"Classes\": "includes/libraries/Classes/"
}
},
}
我试图在其中使用 Contact 类的文件是 admin/controllers/contact/
文件夹中的 edit.php
.我的 edit.php
文件就像:
The file I'm trying to use the Contact class in is edit.php
within the admin/controllers/contact/
folder. My edit.php
file is like:
<?php
use ClassesContact;
$contact = new Contact();
var_dump($contact);
此文件包含 vendor/autoload.php
文件,但我似乎无法让它使用该类?
This file has the vendor/autoload.php
file included, yet I can't seem to get it to use the class?
推荐答案
Classes/Contact/Contact.php
和作曲家规则 "Classes\": "includes/libraries/Classes/"
表示 ClassesContactContact
类,而不是 ClassesContact
.
Classes/Contact/Contact.php
and the composer rule "Classes\": "includes/libraries/Classes/"
imply ClassesContactContact
class, not ClassesContact
.
因此,如果您确实需要 ClassesContact
类,请将 Classes/Contact/Contact.php
文件移至父目录:Classes/Contact.php
.
So if you actually want ClassesContact
class, move the Classes/Contact/Contact.php
file up to the parent directory: Classes/Contact.php
.
但是,如果类的所需命名空间路径是ClassesContactContact
,则更改use
:
If, however, the desired namespace path to the class is ClassesContactContact
, then change the use
:
use ClassesContactContact;
还有命名空间
:
namespace ClassesContact;
class Contact {}
示例
├── composer.json
├── includes
│ └── libraries
│ └── Classes
│ └── Contact
│ └── Contact.php
├── test.php
└── vendor
├── autoload.php
└── composer
├── autoload_classmap.php
├── autoload_namespaces.php
├── autoload_psr4.php
├── autoload_real.php
├── autoload_static.php
├── ClassLoader.php
├── installed.json
└── LICENSE
vendor/
下的文件由composer生成.
The files under vendor/
are generated by composer.
composer.json
{
"name": "testpsr4",
"autoload": {
"psr-4": {
"Classes\": "includes/libraries/Classes"
}
}
}
test.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
use ClassesContactContact;
$c = new Contact;
$c->test();
includes/libraries/Classes/Contact/Contact.php
<?php
namespace ClassesContact;
class Contact {
public function test () {
echo __METHOD__, PHP_EOL;
}
}
测试
composer update
php test.php
输出
ClassesContactContact::test
这篇关于未找到 Composer 自动加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!