Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoloading local composer package

Ive read several questions on this topic, but I still cant figure it out. I have a library that I want to put in the ~/vendor folder and use the built in composer autoloader. My package is called "beep". The directory structure is

vendor/beep
vendor/beep/beep
vendor/beep/beep/src
vendor/beep/beep/src/Beep
vendor/beep/beep/src/Beep/Request.php

Request.php starts with:

namespace Beep;
class Request { ....

composer.json ends with

"autoload": {
   "psr-0": {"Beep\\": "src/Beep"}
}

and still when I try to do:

$r = new Beep\Request();

I get :

Fatal error: Class 'Beep\Request' not found in ....

The autoloading for all other packages is working. I am doing composer update and it claims its generating autoload files.

Any idea what I am doing wrong ?

Thanks

like image 958
gotha Avatar asked Feb 12 '23 15:02

gotha


1 Answers

When you define PSR-0 autoloading, the name of the class will be entirely converted to the path and file name and then appended to the path you say contains the prefix.

In contrast, if you define PSR-4 autoloading, the prefix mentioned gets stripped from the class name, and the remaining parts get converted to a path and file name and then appended to the path.

"psr-0": {"Beep\\": "src/Beep"}

If you autoload a class \Beep\Request, it will be searched at src/Beep/Beep/Request.php.

"psr-4": {"Beep\\": "src/Beep"}

Nearly the same here, but because "Beep" gets stripped of the classname first, the remaining classname is Request, and the search path then is src/Beep/Request.php.

It is however recommended to keep the path length to a minimum, so I would recommend this:

"psr-4": {"Beep\\": "src"}

And then remove the probably empty "Beep" directory (you cannot have a Beep.php file at this level because it cannot contain a valid namespaced class, and any other prefix wouldn't match). Your Beep\Request class would then be located at src/Request.php.

like image 181
Sven Avatar answered Feb 15 '23 09:02

Sven