How does PSR-4 autoloading work in composer for custom libraries?

故事扮演 提交于 2019-12-01 15:11:16

问题


I use the following directory structure based on my understanding of how namespaces in PHP work:

project_root
    app/
    |    lib/
    |    |    MyCompany/
    |    |    |    Utility/
    |    |    |    |    Logger.php
    |    |    |    Core/
    |    |    |    |    User.php
vendor/
    composer/
    symfony/
    guzzle/
bootstrap.php
composer.json

According to the PSR-4 specification, a fully qualified class name has the following form:

\<NamespaceName>(\<SubNamespaceNames>)*\<ClassName>

Question 1:

From my directory structure above, is the assumption below correct?

  • NamespaceName = MyCompany
  • SubNamespaceNames = Utility | Core
  • ClassName = Logger | User

Question 2:

If my bootstrap.php file contains the following:

<?php
require 'vendor/autoload.php';

How would I configure the 'autoload' section of composer.json to autoload the classes in the MyCompany directory? Such that I would be able to create an instance of Logger in bootstrap.php


回答1:


Taken from the documentation you linked:

{
    "autoload": {
        "psr-4": {
            "MyCompany\\": "app/lib/MyCompany/",
        }
    }
}

This is pretty self explanatory, it simply tells the autoloader that app/lib/MyCompany is the root for the MyCompany\ namespace.

You would then be able to use the class as \MyCompany\Utility\Logger.

Note that in PSR-4, unlike PSR-0, you'd normally omit MyCompany from the directory structure, and just use app/lib/.



来源:https://stackoverflow.com/questions/27802179/how-does-psr-4-autoloading-work-in-composer-for-custom-libraries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!