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

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

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, the fully qualified class name is as follows:

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

Question 1:

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

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

Question 2:

If the bootstrap.php file contains the following:

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

How do I configure the 'autoload' section in the composer.json file to autoload classes in the MyCompany directory? That way I could create a Logger instance in bootstrap.php

+6
source share
1 answer

Taken from the documentation you provided:

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

This is pretty clear, it just tells the autoloader that app/lib/MyCompany is the root of the MyCompany\ namespace.

Then you can use the class as \MyCompany\Utility\Logger .

Note that in PSR-4, unlike PSR-0, you usually omit MyCompany from the directory structure and simply use app/lib/ .

+5
source

Source: https://habr.com/ru/post/980599/


All Articles