How to use the composer psr-4

I have one directory that will contain all the "helper" classes and functions. Call the helpers directory .

I want to configure the backup directory PSR-4 to point to this directory :

    "autoload": {
          "psr-4": {
                "": "helpers/"
           }
     }

From the Composer documentation:

... a backup directory in which to search for any namespace.

So, I understand that if my files / classes in this directory have PSR-4 compatible names, my application should find them there.

Now I created a helpers / Logger.php file with the Logger class

What namespace should be for this class to 1) match PSR-4 and 2) just work?

I tried

namespace Logger;

And load the class as

$logger = new Logger();

Class Logger .

( loadClass()) , helpers/Logger.php, - - .

PSR-4 - :

namespace Helpers;

:

$logger = new Helpers\Logger();

\Logger, , helpers/Logger.php .

Composer loadClass() :

    // PSR-4 lookup
    $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;

   ........

    // PSR-4 fallback dirs
    foreach ($this->fallbackDirsPsr4 as $dir) {
        if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
            return $file;
        }
    }

, .

, - PSR-4.

?

Edit

, , , , (, Pimple ):

<?php

require_once __DIR__ . '/vendor/autoload.php';
$app = new \Pimple\Container();

/** Register logger */
$app['logger'] = function ($c) {
    return new Helpers\Logger();
};

$app['logger']->info('test');
+4
1

PSR4 , , helpers, helpers, .

0

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


All Articles