Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP adding custom namespace using autoloader from composer

Here is my folder structure:

Classes   - 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?

like image 688
John Avatar asked Jul 19 '15 19:07

John


1 Answers

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(); 
like image 67
Tomas Votruba Avatar answered Sep 21 '22 21:09

Tomas Votruba