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 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂