dsaob80228 2015-05-31 17:30
浏览 72

Composer包:AutoLoad并扩展另一个包

I was just creating one of my first PHP Packages using Composer and I hit a problem.

Currently I'm working on a package that his main class extends a class from another package, so on my composer.json I've the package I'm extending declared as a requirement:

"require": {
        "php": ">=5.3.0",
        "ext-mbstring": "*",
        "author/BasePackage": "dev-master"
},

And, If I issue composer update I get a nice vendor directory inside my project with the author/BasePackage dependency downloaded there.

So my question is, on my main class file src\Extended.php I need to manually do something like require_once __DIR__ . "/../vendor/autoload.php"; in order to autoload the BasePackage so I can do class Extended extends \BasePackage\BasePackage.

Is this ok? How am I supposed to load my package dependencies? When I commit this package to GitHub or so, I'm ignoring the vendor directory and if someone uses this by requiring it on their projects require_once __DIR__ . "/../vendor/autoload.php"; will fail because it won't be where I expected it to be.

How should I do this?

Thank you.

  • 写回答

1条回答 默认 最新

  • doutuo7609 2015-05-31 17:47
    关注

    No, this is not ok.

    You can safely assume that anyone who is using your package is using Composer. And he will be using Composer's autoloader. So he is able to load both your own class from the package, as well as any other class your package depends on, provided that you listed it as a dependency in your package.

    Don't manually load other classes! You don't have to.

    Your tests in your package should include the vendor/autoload.php in the bootstrapping - this will allow your class to directly be usable, because the other packages classes can be autoloaded as well. Any example scripts should also include the created autoloader.

    If your package is used somewhere else, that autoloader will act the same: All classes that Composer manages to download that have a correct autoload declaration are directly usable after the autoloader has been included.

    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器