douzhuan0309 2015-01-08 05:08
浏览 66
已采纳

Composer autoload - 如何从不同的文件夹中获取类,特征和接口?

How can I use composer autoload to fetch classes, traits, interfaces from different folders?

Some of them I use namespaces, such as,

controller/Foo.php,

namespace MyNamespace;
class Foo
{
    public $message = 'hello Foo';
}

model/Boo.php

namespace MyNamespace;
class Boo
{
    public $message = 'hello Boo';
}

index.php,

// Composer.
require 'vendor/autoload.php';

use \MyNamespace\Foo;
$Foo = new Foo();
var_dump($Foo);

error,

Fatal error: Class 'MyNamespace\Foo' not found in C:...

composer.json,

{
    "autoload": {
        "psr-0": {
            "": "ext/",
            "": "controller/",
            "": "model/" 
        }
    }
}

I have many classes in many different folders (it may expand), so is there any way without re-installing composer autoload when I have new classes in a fresh folder?

  • 写回答

1条回答 默认 最新

  • dongwen7380 2015-01-08 05:18
    关注

    You have to standardize your namespaces and folders structure. If you have the same namespace in different folders, it's harder to create a simple logic to autoload them all. Try to use another segment in your namespace like:

    namespace MyNamespace\Controller;
    class Foo
    {
        public $message = 'hello Foo';
    }
    

    and:

    namespace MyNamespace\Model;
    class Boo
    {
        public $message = 'hello Boo';
    }
    

    and in your composer.json:

    {
        //..
        "autoload": {
            "psr-4": {
                 "MyNamespace\\Model\\": "/path/to/model/folder/",
                 "MyNamespace\\Controller\\": "/path/to/controller/folder/"
            }
        }
    }
    

    after setting this up, call:

    composer dump-autoload
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作