Nao000のぶろぐ

蝶を追っている少年になりたい

PHP の Composer と PSR-4 のオートロードを改めて観察する

はじめに

  • オートロードがどういう処理を行っているかは追ってないです
  • spl_autoload_register を使ってなにかしてる認識でいます

Composer を使った PSR-4 のオートロードがない場合

別ファイルに定義された class を使う場合は require_once などでファイルを読み込む必要があります。

<?php
require_once "src/controller/index.php";
require_once "src/view/index.php";
require_once "src/model/index.php";

$Controller_Index = new App\Controller\Index();
$Controller_Index->index();

$View_Index = new App\View\Index();
$View_Index->index();

$Model_Index = new App\Model\Index();
$Model_Index->index();

各クラスの内容は echo を実行しているだけです。

例として src/controller/index.php は以下の様になっています。

<?php
namespace App\Controller;
final class Index
{
    public function index()
    {
        echo 'Hello From <'.__METHOD__.'>'.PHP_EOL;
    }
}

実行結果

root@b1bb52df23b4:/shared-app/learn-autoload# php index.php
Hello From <App\Controller\Index::index>
Hello From <App\View\Index::index>
Hello From <App\Model\Index::index>
root@b1bb52df23b4:/shared-app/learn-autoload#

Composer で PSR-4 のオートロードを使う場合

こうなります。同じ結果が得られます。

<?php
require_once "vendor/autoload.php";

$Controller_Index = new App\Controller\Index();
$Controller_Index->index();

$View_Index = new App\View\Index();
$View_Index->index();

$Model_Index = new App\Model\Index();
$Model_Index->index();

以下の3つの require_once が無くなっていることが注目ポイントです。

require_once "src/controller/index.php";
require_once "src/view/index.php";
require_once "src/model/index.php";

Composer と PSR-4 の関係

そもそも PSR-4 は PSR の勧告の1つで、内容はオートロードについての勧告の認識でいます。

「PSR-4 に準拠したオートロードを実装する」みたいな言葉の使い方が正しいと思っています。

Compsoer はあくまでパッケージ管理ツールであって、オプションで PSR-4 に準拠したオートロードが使えるよ っていう認識でいます。

compoer init を実行していくと以下の様に質問されます。

Add PSR-4 autoload mapping? Maps namespace "Root\LearnAutoload" to the entered relative path. [src/, n to skip]:

そもそも「勧告」っていう言葉に馴染みないです。W3C 関連でなにか調べたときにも「勧告」という言葉見たことがある程度です。

「こういう行動をしてください。強制ではないけど。」みたいな認識でいます。

composer.json

composer init で作ったもの

{
    "name": "root/learn-autoload",
    "type": "project",
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "require": {}
}

ディレクトリ構造

root@b1bb52df23b4:/shared-app/learn-autoload# tree
.
├── composer.json
├── index.php
├── src
│   ├── controller
│   │   └── index.php
│   ├── model
│   │   └── index.php
│   └── view
│       └── index.php
└── vendor
    ├── autoload.php
    └── composer
        ├── ClassLoader.php
        ├── LICENSE
        ├── autoload_classmap.php
        ├── autoload_namespaces.php
        ├── autoload_psr4.php
        ├── autoload_real.php
        └── autoload_static.php

6 directories, 13 files
root@b1bb52df23b4:/shared-app/learn-autoload#

参考