PHpullh
학습 라이브러리/PHP/Attribute 기반 컨트롤러 메타데이터

PHP · 객체지향

Attribute 기반 컨트롤러 메타데이터

클래스에 붙인 Attribute를 라우팅이나 미들웨어 설정에 활용하는 예제입니다.

객체지향고급attributecontrollerreflection

핵심 설명

클래스에 붙인 Attribute를 라우팅이나 미들웨어 설정에 활용하는 예제입니다.

PHP code

<?php
#[Attribute]
class Middleware {
    public function __construct(public string $name) {}
}

#[Middleware('auth')]
class DashboardController {}

$ref = new ReflectionClass(DashboardController::class);
echo $ref->getAttributes(Middleware::class)[0]->newInstance()->name;

학습 팁

클래스 예제는 생성자, 가시성, 협력 객체의 책임을 함께 보면 실무 감각이 빨리 붙습니다.

주의할 점

가시성, final, readonly 제약을 무시하면 객체 설계가 금방 흐트러집니다.

자주 묻는 질문

Attribute 기반 컨트롤러 메타데이터란 무엇인가요?

클래스에 붙인 Attribute를 라우팅이나 미들웨어 설정에 활용하는 예제입니다.

Attribute 기반 컨트롤러 메타데이터 학습 시 주의할 점은 무엇인가요?

가시성, final, readonly 제약을 무시하면 객체 설계가 금방 흐트러집니다.