PHP 프로젝트 표준 폴더
| 자리 | 들어가는 것 |
|---|
public/ | 웹 서버의 뿌리(document root). 앞문 index.php 와 CSS·그림만 둬요. 이 폴더 밖 파일은 주소로 열 수 없어요. |
|---|
public/index.php | 앞문(front controller). 모든 요청이 여기로 들어와 주소를 보고 알맞은 코드로 보내요. |
|---|
src/ | 클래스 코드. PSR-4 로 App\Greeting 은 src/Greeting.php 에 있어요. |
|---|
config/ | 설정 파일. 비밀번호·키는 적지 않고 환경 변수에서 읽어요. |
|---|
templates/ | HTML 을 만드는 PHP 파일. 계산은 하지 않고 받은 값을 이스케이프해서 찍기만 해요. |
|---|
tests/ | 시험 코드(PHPUnit). 운영 서버에는 올리지 않아도 돼요. |
|---|
vendor/ | Composer 가 받은 꾸러미와 autoload.php. 직접 고치지 않고 git 에도 올리지 않아요. |
|---|
var/ | 기록·캐시처럼 실행하며 생기는 파일. git 에 올리지 않아요. |
|---|
웹 뿌리를 public/ 하나로 두면 config/·src/·vendor/ 의 파일이 주소로 새어 나갈 일이 없어요. 공유 호스팅에서 뿌리를 못 바꾸면 public/ 안의 내용을 뿌리에 두고 나머지는 한 단계 위 폴더에 둬요.
계층 나누기
요청을 받는 곳(컨트롤러), 규칙을 판단하는 곳(서비스), 자료를 넣고 꺼내는 곳(저장소)을 다른 클래스에 둬요. 앞문 → 컨트롤러 → 서비스 → 저장소 차례로만 부르고 거꾸로는 부르지 않아요.
이렇게 나누면 저장소를 배열에서 MySQL 로 바꿔도 서비스는 그대로이고, 서비스 규칙은 웹 서버 없이 PHPUnit 으로 시험해요.
- 컨트롤러는
$_GET·$_POST 를 읽고 응답을 만들 뿐 계산하지 않아요. - 서비스는 규칙을 판단해요.
$_GET 이 무엇인지 몰라요. - 저장소는 인터페이스로 꼴을 정해 두면 배열·DB 구현을 바꿔 끼워요.
이름 짓기와 PSR
Composer 꾸러미 이름은 vendor/package 처럼 소문자와 - 를, 이름공간은 App 이나 Acme\Shop 처럼 대문자로 시작하는 낱말을 사용해요.
- PSR-1: 클래스는
StudlyCaps, 메서드는 camelCase, 상수는 UPPER_CASE. - PSR-4: 이름공간 앞부분을 폴더 하나에 잇고, 나머지 이름이 그대로 경로가 돼요(
App\Http\Router → src/Http/Router.php). - PSR-12: 빈칸 넷 들여쓰기, 클래스·메서드 여는 중괄호는 다음 줄, 파일 끝
?> 는 사용하지 않음. - 비밀번호·API 키는 코드에 적지 말고
getenv() 로 받아요.
PHP 는 익명 함수(Closure)와 익명 클래스가 있어서 작은 꼴은 클래스를 덜 사용해도 돼요. 모두 서버 PHP 와 브라우저 PHP 로 돌려 본 코드예요.
싱글톤 · 하나만 있어야 할 때
생성자를 private 으로 막고, static 칸에 처음 만든 객체를 기억해 두었다가 늘 그것을 돌려줘요. ??= 는 비어 있을 때만 넣는 짧은 꼴이에요.
PHP 는 요청마다 새로 시작해서 "하나"도 한 요청 안에서만이에요. 시험하기 어려워지니, 대부분은 앞문에서 하나 만들어 생성자로 넘기는(의존성 주입) 쪽이 나아요.
<?phpdeclare(strict_types=1); final class Settings{ private static ?Settings $instance = null; private array $values = ['lang' => 'en']; private function __construct() { } public static function get(): Settings { return self::$instance ??= new Settings(); } public function set(string $key, string $value): void { $this->values[$key] = $value; } public function value(string $key): string { return $this->values[$key] ?? ''; }} $a = Settings::get();$b = Settings::get();$b->set('lang', 'ko');var_dump($a === $b);echo $a->value('lang'), "\n";
실행 결과
bool(true)ko
팩토리 · 무엇을 만들지 한 곳에서 정할 때
형식 이름을 보고 알맞은 내보내기 객체를 골라 줘요. match 는 맞는 갈래가 없으면 default 로 가고, 거기서 예외를 던질 수 있어요(8.0 부터 throw 가 식). 대소문자도 여기서 한 번에 맞춰요.
<?phpdeclare(strict_types=1); interface Exporter{ public function export(array $row): string;} final class CsvExporter implements Exporter{ public function export(array $row): string { return implode(',', $row); }} final class JsonExporter implements Exporter{ public function export(array $row): string { return json_encode($row); }} final class ExporterFactory{ public static function for(string $format): Exporter { return match (strtolower($format)) { 'csv' => new CsvExporter(), 'json' => new JsonExporter(), default => throw new InvalidArgumentException("unknown format: $format"), }; }} $row = ['id' => 7, 'name' => 'Lee'];echo ExporterFactory::for('CSV')->export($row), "\n";echo ExporterFactory::for('json')->export($row), "\n";try { ExporterFactory::for('xml');} catch (InvalidArgumentException $e) { echo $e->getMessage(), "\n";}
실행 결과
7,Lee{"id":7,"name":"Lee"}unknown format: xml전략 · 바꿔 끼우는 계산 방법
할인 규칙을 화살표 함수(fn)로 만들어 Cart 에 넘겨요. 속성에 든 함수는 ($this->discount)(...) 처럼 괄호로 감싸 불러요. $coupon(3000) 처럼 설정이 필요한 규칙은 함수를 돌려주는 함수예요.
<?phpdeclare(strict_types=1); final class Cart{ /** @param callable(int): int $discount */ public function __construct(private int $total, private $discount) { } public function pay(): int { return ($this->discount)($this->total); }} $none = fn(int $t): int => $t;$tenPercent = fn(int $t): int => $t - intdiv($t, 10);$coupon = fn(int $off): Closure => fn(int $t): int => max(0, $t - $off); foreach ([$none, $tenPercent, $coupon(3000)] as $rule) { echo (new Cart(20000, $rule))->pay(), "\n";}
실행 결과
200001800017000
옵서버 · 일이 생기면 알려 주기
재입고 같은 일이 생기면 등록해 둔 함수들을 차례로 불러요. 바깥 배열을 바꾸려면 use (&$log) 처럼 참조로 받아야 해요. 그냥 use ($log) 면 사본이 바뀌어요.
<?phpdeclare(strict_types=1); final class Stock{ /** @var list<callable(string): void> */ private array $listeners = []; public function onRestock(callable $fn): void { $this->listeners[] = $fn; } public function restock(string $item): void { foreach ($this->listeners as $fn) { $fn($item); } }} $log = [];$stock = new Stock();$stock->onRestock(function (string $item): void { echo "Mail: $item is back\n";});$stock->onRestock(function (string $item) use (&$log): void { $log[] = $item;});$stock->restock('keyboard');echo 'Log: ', implode(',', $log), "\n";
실행 결과
Mail: keyboard is backLog: keyboard
의존성 주입 · 필요한 것을 생성자로 받기
Greeter 는 회원 저장소를 스스로 만들지 않고 생성자로 받아요. 평소에는 ArrayUserStore(나중에 DB 버전)를, 시험에서는 익명 클래스(new class implements UserStore)로 만든 가짜를 넣어요.
Symfony·Laravel 의 서비스 컨테이너도 결국 생성자 자료형을 보고 알맞은 객체를 찾아 넣어 주는 일을 해요.
<?phpdeclare(strict_types=1); interface UserStore{ public function find(int $id): ?string;} final class ArrayUserStore implements UserStore{ public function __construct(private array $names) { } public function find(int $id): ?string { return $this->names[$id] ?? null; }} final class Greeter{ public function __construct(private UserStore $users) { } public function hello(int $id): string { return 'Hello, ' . ($this->users->find($id) ?? 'guest'); }} $greeter = new Greeter(new ArrayUserStore([1 => 'Hana']));echo $greeter->hello(1), "\n";echo $greeter->hello(2), "\n"; $fake = new class implements UserStore { public function find(int $id): ?string { return 'Tester'; }};echo (new Greeter($fake))->hello(99), "\n";
실행 결과
Hello, HanaHello, guestHello, Tester