It's my first time using Composer and I'm getting a little bit batty trying to figure out why it is not picking up my namespaces.
In my project/
directory:
├── composer.json
├── composer.lock
├── composer.phar
├── README.md
├── vendor (truncated)
└── src
├── Config.php
├── Handler.php
└── Router.php
src/Config.php
<?php
$project_root = realpath(__DIR__ . '/..');
$autoload = $project_root . '/vendor/autoload.php';
?>
src/Router.php
<?php namespace Project\Router;
include_once("Config.php");
require $autoload;
use Project\Handler;
Hello::world();
?>
src/Handler.php
<?php namespace Project\Handler;
include_once("Config.php");
require $autoload;
class Hello {
public function world() {
echo "Hello world!";
}
}
?>
composer.json
{
"autoload": {
"psr-4": {
"Project\\": "src"
}
}
}
http://127.0.1.1/project/src/Router.php
:
Fatal error: Uncaught Error: Class 'Project\Router\Hello' not found in /path/to/project/src/Router.php:38(not actual line) Stack trace: #0 {main} thrown in /path/to/project/src/Router.php on line 38(not actual line)
I am able to use foreign dependencies so my general Composer setup seems ok. I just can't figure out where I'm screwing up on my own namespaces.
You appear to be misinterpreting how PSR4 works.
"autoload": {
"psr-4": {
"Project\\": "src"
}
}
This config means if you request the class Project\Handler\Hello from the autoloader it is going to check the path src\Handler\Hello.php
(Which doesn't exist.)
If you change your directory structure to the following it will work:
└── src
├── Config.php
├── Router.php
└── Handler
└── Hello.php (renamed from Handler.php)
Also, neither Config.php or Router.php contain classes, which defeats the point of using a class autoloader.
Give this a read: http://www.php-fig.org/psr/psr-4/
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments