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 UltraScale 系列 Bitslip 技术支持
  • ¥15 一个线程在sleep的时候set一个信号会起作用吗
  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败
  • ¥15 Sqlserver查询链接服务器数据问题
  • ¥15 Bibtex4Word 引用中文文献