duanfei8149
duanfei8149
2017-05-05 11:02
浏览 112
已采纳

如何使用composer autoloader自动加载我的类?

By considering this files structure

| -- src /
        | -- vendor
        | -- models
        | -- libraries
        | -- ...
        | -- composer.json

How can I autoload classes located in 'models' & 'libraries' directories ?

图片转代码服务由CSDN问答提供 功能建议

通过考虑此文件结构

  |  -  src / 
 |  - 供应商
 |  - 型号
 |  - 图书馆
 |  -  ... 
 |  -  composer.json 
   
 
 

如何在“模型”和“模型”中自动加载类? 'libraries'目录?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongtao1262
    dongtao1262 2017-05-05 11:21
    已采纳

    You can add your own autoloader rules into the composer.json file in your project - this adds your own rules to the vendor/autoload.php file so that your own classes will load as well as the ones in the vendor/ directory. There's more information in the docs here: https://getcomposer.org/doc/04-schema.md#autoload. Take a look at the PSR-0 section to load classes from your two directories.

    Try something like:

    {
        "autoload": {
            "psr-0": { "": ["models/", "libraries"] }
        }
    }
    

    If your classes are namespaced, then specify the namespaces as this will stop composer from looking for all classes in those directories.

    点赞 评论
  • doulu1945
    doulu1945 2019-03-23 09:23

    Or later in code you can add your lib, example:

    $loader = require(ROOTDIR . 'vendor/autoload.php'); // composer autoloading
    //public function addPsr4($prefix, $paths, $prepend = false)
    $loader->addPsr4('extend\\', ROOTDIR . 'class/lib'); 
    
    $a = new \extend\MyClass(); // MyClass.php is in ROOTDIR/class/lib directory
    
    点赞 评论

相关推荐