且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PSR-4 自动加载如何在 composer 中为自定义库工作?

更新时间:2022-10-22 17:04:55

取自您链接的文档:

{自动加载":{psr-4":{"MyCompany\": "app/lib/MyCompany/",}}}

这很容易解释,它只是告诉自动加载器 app/lib/MyCompanyMyCompany 命名空间的根.

然后您就可以将该类用作 MyCompanyUtilityLogger.

请注意,在 PSR-4 中,与 PSR-0 不同,您通常会从目录结构中省略 MyCompany,而只使用 app/lib/.p>

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

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 MyCompanyUtilityLogger.

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