John John - 10 months ago 65
PHP Question

PHP adding custom namespace using autoloader from composer

Here is my folder structure:

- CronJobs
- Weather
- WeatherSite.php

I want to load WeatherSite class from my script. Im using composer with autoload:

$loader = include(LIBRARY .'autoload.php');
$loader->add('Classes\Weather',CLASSES .'cronjobs/weather');
$weather = new Classes\Weather\WeatherSite();

Im assuming the above code is adding the namespace and the path that namespace resolves to. But when the page loads I always get this error:

Fatal error: Class 'Classes\Weather\WeatherSite' not found

Here is my WeatherSite.php file:

namespace Classes\Weather;

class WeatherSite {

public function __construct()


public function findWeatherSites()



What am I doing wrong?

Answer Source

You actually don't need custom autoloader, you can use PSR-4.

Update your autoload section in composer.json:

"autoload": {
     "psr-4": {"Classes\\Weather\\": "Classes/CronJobs/Weather"}

To explain: it's {"Namespace\\": "directory to be found in"}

Don't forget to run composer dump-autoload to update Composer cache.

Then you can use it like this:

include(LIBRARY .'autoload.php');

$weather = new Classes\Weather\WeatherSite();