PHP adding custom namespace using autoloader from composer

旧时模样 提交于 2019-11-27 01:34:37

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/31504980/php-adding-custom-namespace-using-autoloader-from-composer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!