autoload with composer


spl_autoload_register 를 직접 명령어로 구현하는 것이 아니라


composer를 통해서 라이브러리를 설치하는 경우 자동으로 autoload.php가 설치된다


( 경로 : vendor/autoload.php )


이때 composer.json 파일에 


{
"require": {
"slim/slim": "3.0",
"monolog/monolog": "^1.23"
},
"autoload": {
"psr-4" : {
"App\\": "app"
}
}
}


처럼 autoload를 등록하면 app 이라고 사용되는 폴더를 App 이라는 namespace 를 

통해서 사용할 수 있다.



/app/Test.php

<?php

namespace App;

class Test
{
public function __construct()
{
echo "test class";
}
}


/public/index.php

<?php

require __DIR__ . '/../vendor/autoload.php';

use App;

$test = new \App\Test;


결과


test class



더욱 자세한 학습은 다음의 링크와 글을 참조 


https://phpenthusiast.com/blog/how-to-autoload-with-composer


https://getcomposer.org/doc/01-basic-usage.md#autoloading

Autoloading#

For libraries that specify autoload information, Composer generates a vendor/autoload.php file. You can simply include this file and start using the classes that those libraries provide without any extra work:

require __DIR__ . '/vendor/autoload.php';

$log = new Monolog\Logger('name');
$log->pushHandler(new Monolog\Handler\StreamHandler('app.log', Monolog\Logger::WARNING));
$log->addWarning('Foo');

You can even add your own code to the autoloader by adding an autoload field to composer.json.

{
    "autoload": {
        "psr-4": {"Acme\\": "src/"}
    }
}

Composer will register a PSR-4 autoloader for the Acme namespace.

You define a mapping from namespaces to directories. The src directory would be in your project root, on the same level as vendor directory is. An example filename would be src/Foo.php containing an Acme\Foo class.

After adding the autoload field, you have to re-run dump-autoload to re-generate the vendor/autoload.php file.

Including that file will also return the autoloader instance, so you can store the return value of the include call in a variable and add more namespaces. This can be useful for autoloading classes in a test suite, for example.

$loader = require __DIR__ . '/vendor/autoload.php';
$loader->addPsr4('Acme\\Test\\', __DIR__);

In addition to PSR-4 autoloading, Composer also supports PSR-0, classmap and files autoloading. See the autoload reference for more information.

See also the docs on optimizing the autoloader.

Note: Composer provides its own autoloader. If you don't want to use that one, you can include vendor/composer/autoload_*.php files, which return associative arrays allowing you to configure your own autoloader.



'■ 백엔드 ■ > Modern PHP' 카테고리의 다른 글

autoload with composer  (0) 2018.07.01
autoload : spl_autoload_register  (0) 2018.07.01
Posted by SAP (Study And Programming) by serpiko

댓글을 달아 주세요