dongluo3331 2018-03-27 22:04
浏览 19
已采纳

作曲家 - 如何获得项目的根?

I'm trying to use the Composer autoloader located at vendor/autoload.php. However, I can't seem to figure out how to get to the root of the project, from which I could then navigate to vendor/autoload.php. I'm having to specify the relative path in each file (i.e. ../../../vendor/autoload.php). This seems like a very nasty way to get to the autoloader, since this path will be different depending on how deep the file is.

Is there a way to get to the root directory without specifying a relative path, or do I need to go up x parent directories in every file?

  • 写回答

1条回答 默认 最新

  • drasebt1835 2018-03-27 22:23
    关注

    PHP has no way of knowing what the "root of the project" is. You could have any number of directories on your disk, with files called vendor/autoload.php in several of them, and only you know what's special about the "project root". So ultimately, the answer is no, there is no way.

    However, note that you only need to include the autoloader in files which aren't themselves included or autoloaded. The autoloader is something you load once, as part of the configuration / bootstrapping of your code, and it then loads whatever classes it needs wherever they're referenced.

    So the way to limit the mess of different levels is to structure your project carefully. For instance:

    • Route all requests via one or two "routers", such as a single "index.php" file. Use Apache mod_rewrite or the equivalent in Nginx etc to make all URLs actually load this script, and then in the script work out what code to run based on the URL. You can use libraries such as nikic/FastRoute to translate the URLs into functions to call, which will then be autoloaded.
    • Use different PHP files, but all in a reasonably flat directory structure, so that they all have to "climb" the same number of levels to reach the project root.

    The same principle applies to use in command-line scripts or any other kind of application: limit or structure the "entry points", because only those need to know where to load the autoloader.

    If you already have some kind of config file loaded on every request / script run / unit test / etc, it might be sensible to put the require_once 'vendor/autoload.php'; line in there. Like the configuration, the autoloader is "global state" that you want to just set up once and then forget about.

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

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程