I have folder structure like:
includes/
libraries/
Classes/
Contact/
Contact.php
ContactController.php
admin/
controllers/
contact/
edit.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');
}
}
I have my composer.json file like:
{
"autoload": {
"psr-4": {
"Classes\\": "includes/libraries/Classes/"
}
},
}
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 Classes\Contact;
$contact = new Contact();
var_dump($contact);
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
and the composer rule "Classes\\": "includes/libraries/Classes/"
imply Classes\Contact\Contact
class, not Classes\Contact
.
So if you actually want Classes\Contact
class, move the Classes/Contact/Contact.php
file up to the parent directory: Classes/Contact.php
.
If, however, the desired namespace path to the class is Classes\Contact\Contact
, then change the use
:
use Classes\Contact\Contact;
And the namespace
:
namespace Classes\Contact;
class Contact {}
Example
├── 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
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 Classes\Contact\Contact;
$c = new Contact;
$c->test();
includes/libraries/Classes/Contact/Contact.php
<?php
namespace Classes\Contact;
class Contact {
public function test () {
echo __METHOD__, PHP_EOL;
}
}
Testing
composer update
php test.php
Output
Classes\Contact\Contact::test
来源:https://stackoverflow.com/questions/40126706/composer-autoloading-classes-not-found