PSR-4 오토로딩 표준
Coddy PHP 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 91개 중 12번째.
PSR-4는 PHP classes가 namespace와 file 위치를 기반으로 자동으로 로드되는 방식을 정의하는 표준입니다. 각 class file을 수동으로 포함하는 대신, PSR-4를 사용하면 PHP가 해당 class를 사용할 때 자동으로 찾아 로드할 수 있습니다.
핵심 규칙은 간단합니다. namespace는 directory 구조와 일치해야 합니다. App\Models\User class가 있다면 파일은 App/Models/User.php에 위치해야 합니다.
<?php
// 파일: src/Models/User.php
namespace App\Models;
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
PSR-4 규칙을 따르는 간단한 autoloader function을 작성할 수 있습니다:
<?php
// 파일: autoload.php
spl_autoload_register(function ($class) {
$prefix = 'App\\';
$baseDir = __DIR__ . '/src/';
// 클래스가 우리의 네임스페이스 접두사를 사용하는지 확인
if (strpos($class, $prefix) === 0) {
$relativeClass = substr($class, strlen($prefix));
$file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';
if (file_exists($file)) {
require $file;
}
}
});
spl_autoload_register function은 PHP가 알 수 없는 class를 만날 때마다 사용자의 function을 호출하도록 합니다. 이 function은 namespace를 file path로 변환하고 이를 로드합니다.
핵심 요점: PSR-4는 네임스페이스와 파일 경로 사이에 예측 가능한 매핑을 만듭니다. App\Models\User를 보면, file이 src/Models/User.php에 있다는 것을 즉시 알 수 있습니다. 이 규칙을 사용하면 프로젝트를 탐색하고 유지 관리하기가 더 쉬워집니다.
챌린지
쉬움네임스페이스와 파일 위치를 기반으로 클래스를 자동으로 로드하는 간단한 PSR-4 autoloading 시스템을 만들어 보겠습니다.
PSR-4가 네임스페이스를 directory 경로에 매핑하는 방식을 보여 주는 세 개의 file로 구성된 프로젝트를 만들 것입니다.
src/Services/Logger.php:App\Servicesnamespace에Loggerclass를 Define합니다.public $nameproperty, name을 accepts하고 설정하는 constructor, 그리고log($message)method를 가져야 하며, 이 method는"[name] logged: [message]"를 반환해야 합니다.src/Services/Mailer.php:App\Servicesnamespace에Mailerclass를 Define합니다.public $senderproperty, sender를 accepts하고 설정하는 constructor, 그리고send($to)method를 가져야 하며, 이 method는"Mail from [sender] to [to]"를 반환해야 합니다.main.php:spl_autoload_register를 사용하여App\namespace prefix를src/directory에 매핑하는 PSR-4 autoloader를 Create합니다. autoloader는 namespace separator를 directory separator로 Convert하고 올바른 file을 찾기 위해.php를 추가해야 합니다. autoloader를 등록한 후usekeyword를 사용하여 두 class를 모두 import한 다음, name이"FileLogger"인Logger와 sender가"admin@site.com"인Mailer를 Create합니다. logger에서log("System started")를 호출한 결과와 mailer에서send("user@example.com")을 호출한 결과를 Print합니다(각각 별도의 줄에).
핵심 개념은 autoloader function이 정규화된 class name(예: App\Services\Logger)을 받고 이를 file path(src/Services/Logger.php)로 Convert해야 한다는 것입니다. strpos를 사용하여 class가 namespace prefix로 시작하는지 확인하고, substr을 사용하여 relative class name을 가져오며, str_replace를 사용하여 backslash를 forward slash로 Convert하세요.
직접 해보기
<?php
// PSR-4 오토로더 구현
// TODO: spl_autoload_register를 사용하여 오토로더 등록
// 오토로더는 다음을 수행해야 합니다:
// 1. 클래스가 'App\' 네임스페이스 접두사로 시작하는지 확인
// 2. 'App\' 접두사를 제거하여 상대 클래스 이름 가져오기
// 3. 네임스페이스 구분자(\)를 디렉터리 구분자(/)로 변환
// 4. 'src/'를 앞에 붙이고 '.php'를 뒤에 붙여 파일 경로 생성
// 5. 파일이 존재하면 require
spl_autoload_register(function ($class) {
// TODO: 네임스페이스 접두사와 기본 디렉터리 정의
// TODO: 클래스가 네임스페이스 접두사를 사용하는지 확인 (strpos 사용)
// TODO: 상대 클래스 이름 가져오기 (substr 사용)
// TODO: \를 /로 바꿔 파일 경로 생성 (str_replace 사용)
// TODO: 파일이 존재하면 require 하세요
});
// TODO: 'use' 키워드를 사용하여 Logger와 Mailer 클래스를 가져오세요
// TODO: 이름이 "FileLogger"인 Logger 인스턴스를 생성하세요
// TODO: 발신자가 "admin@site.com"인 Mailer 인스턴스를 생성하세요
// TODO: log("System started")의 결과를 출력하세요
// TODO: send("user@example.com")의 결과를 출력하세요
?>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러