dongnue2071 2015-12-26 19:46
浏览 112
已采纳

Composer:加载自定义类

I've just started to work with Composer, but I can't really grasp how I should solve the following issue: how do I set up so I don't have to state \Other\ when using a class? (i.e. so my custom classes works like the Mustache classes)

This works

$mustache = new Mustache_Engine();
$foo = new \Other\SimpleClass();

This does not work

$foo = new SimpleClass();

composer.json

{
  "autoload": {
    "psr-0": {
        "Other": "lib/",
        "Mustache": "lib/"
    }
}
}

Folder structure

/lib
  /Mustache
  /Other

I have entered namespace Other; in all files in my Other-folder

  • 写回答

1条回答 默认 最新

  • dou6577 2015-12-28 16:17
    关注

    how do I set up so I don't have to state \Other\ when using a class?

    Don't strive for not using namespaces.

    Not using namespaces makes only sense for really small scripts, which run standalone and don't reuse pieces of code from other vendors (components/libraries).

    I still don't understand why $mustache = new Mustache_Engine(); doesn't have to be $mustache = new \Mustache\Mustache_Engine();

    Mustache_Engine is not namespaced (yet).

    They use a string-prefix-namespace: they simply add Mustache_ to the classname Engine to avoid class name collision with other classes called Engine. This code will run on old and newer PHP versions.

    Eventually, it will be come \Mustache\Engine, when the Mustache developers update the code to make use of namespaces. This code will only run on PHP versions, which support namespaces as a language feature.

    Autoloading of Mustache

    If you installed Mustache using Composer

    {
        "require": {
            "mustache/mustache": "^2.9"
        }
    }
    

    then Composer will generate the autoloading for Mustache automatically.

    You don't have to add a PSR-0 directive to composer.json to get it working.

    You only need to set PSR-0, if you downloaded and extracted Mustache manually into the /lib folder. This is the old way of working with dependencies - leverage Composer instead.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器