차량 대여 서비스
Coddy PHP 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 91개 중 91번째.
챌린지
쉬움Vehicle Rental Service 시스템을 구축해 보세요. 이 시스템은 차량 보유 목록을 관리하고, 고객의 대여 내역을 추적하며, 차량 유형을 기준으로 요금을 계산합니다. 이 종합적인 도전 과제에서는 상속, 인터페이스, 캡슐화 및 State 패턴을 함께 활용하여 현실적인 대여 비즈니스 애플리케이션을 만듭니다.
코드를 일곱 개의 파일로 구성합니다.
VehicleState.php: 차량이 가질 수 있는 다양한 상태를 나타내는VehicleState인터페이스를 정의합니다. 두 메서드getStatus(): string및canRent(): bool을 포함합니다. 그런 다음 이 인터페이스를 구현하는 세 클래스를 만듭니다.AvailableState:"Available"및true를 반환RentedState:"Rented"및false를 반환MaintenanceState:"Maintenance"및false를 반환
Vehicle.php: VehicleState 파일을 포함합니다.licensePlate(string, public readonly),brand(string, public readonly),dailyRate(float, protected)에 생성자 프로퍼티 승격을 사용하는 추상Vehicle클래스를 만듭니다. 현재 상태는 private 프로퍼티에 저장하며, 기본값은AvailableState입니다. 다음을 구현합니다.getState(): VehicleState: 현재 상태를 반환setState(VehicleState $state): void: 상태를 변경getStatus(): string: 상태의getStatus()에 위임canRent(): bool: 상태의canRent()에 위임abstract calculateCost(int $days): float: 각 차량 유형이 서로 다른 방식으로 요금을 계산getType(): string:static::class를 사용하여 클래스 이름을 반환
Vehicles.php: Vehicle 파일을 포함합니다. 다음 세 개의 구체적인 차량 클래스를 만듭니다.Car: Vehicle을 확장하며,calculateCost()는dailyRate * days를 반환Motorcycle: Vehicle을 확장하며,calculateCost()는dailyRate * days * 0.8을 반환 (20% 할인)Van: 추가적인$mileageRate(float) 매개변수와 함께 Vehicle을 확장하며,calculateCost(int $days, int $miles = 0)는(dailyRate * days) + (mileageRate * miles)를 반환
Customer.php:id(int, public readonly) 및name(string, public readonly)에 생성자 프로퍼티 승격을 사용하는Customer클래스를 만듭니다. 대여 내역은 private 배열에 기록합니다. 다음을 구현합니다.addRental(string $vehiclePlate, float $cost): void: 내역에 추가getRentalCount(): int: 대여 횟수를 반환getTotalSpent(): float: 모든 대여 비용의 합계를 반환
Rental.php: Vehicle 및 Customer 파일을 포함합니다. 고객과 차량을 연결하는Rental클래스를 만듭니다.customer(Customer, public readonly),vehicle(Vehicle, public readonly),days(int, private), 선택 사항인miles(int, private, 기본값 0)에 생성자 프로퍼티 승격을 사용합니다. 다음을 구현합니다.calculateTotal(): float: vehicle이 Van이면 miles를calculateCost()에 전달하고, 그렇지 않으면 days만 전달complete(): string: 합계를 계산하고, 고객의 내역에 추가하며, vehicle을 AvailableState로 설정하고,"Rental completed: $[total]"을 반환 (소수점 이하 2자리)
RentalService.php: Rental 및 Vehicles 파일을 포함합니다. 차량 보유 목록을 관리하는RentalService클래스를 만듭니다. 차량은 license plate를 인덱스로 사용하는 private 배열에 저장합니다. 다음을 구현합니다.addVehicle(Vehicle $vehicle): void: 보유 목록에 추가findVehicle(string $plate): ?Vehicle: vehicle 또는 null을 반환getAvailableVehicles(): array:canRent()가 true인 차량을 반환rentVehicle(Customer $customer, string $plate, int $days, int $miles = 0): string|Rental: vehicle을 찾지 못하면"Vehicle not found"를 반환하고, 이용할 수 없으면"Vehicle is not available"을 반환합니다. 그렇지 않으면 vehicle을 RentedState로 설정하고 새로운 Rental 객체를 반환합니다.setMaintenance(string $plate): string: vehicle을 MaintenanceState로 설정하고,"[plate] set to maintenance"또는"Vehicle not found"를 반환
main.php: RentalService 및 Customer 파일을 포함합니다. fleet 데이터(JSON), customer 데이터(JSON), operations(JSON)이라는 세 가지 입력을 받습니다.Fleet JSON 형식:
[{"type": "car", "plate": "CAR-001", "brand": "Toyota", "rate": 50}, {"type": "van", "plate": "VAN-001", "brand": "Ford", "rate": 80, "mileage_rate": 0.25}]Customer JSON 형식:
{"id": 1, "name": "Alice"}Operations JSON 형식:
[{"op": "available"}, {"op": "rent", "plate": "CAR-001", "days": 3}, {"op": "complete", "plate": "CAR-001"}, {"op": "maintenance", "plate": "VAN-001"}, {"op": "customer_stats"}]rental service를 생성하고, 모든 vehicle을 fleet에 추가한 다음 customer를 생성합니다. plate별로 active rentals를 추적합니다. 각 operation을 처리합니다.
"available":"Available vehicles: [count]"를 출력"rent": vehicle을 대여합니다. 성공하면 Rental을 저장하고"Rented [plate] for [days] days"를 출력합니다. Van이면 operation의 miles를 포함하고, 그렇지 않으면 오류 메시지를 출력합니다."complete": 해당 plate에 저장된 rental을 완료하고 결과를 출력"maintenance":setMaintenance()의 결과를 출력"status": 지정된 plate에 대해"[plate]: [status]"를 출력"customer_stats":"[name]: [count] rentals, $[total] spent"를 출력 (소수점 이하 2자리)
각 결과를 새 줄에 출력합니다.
이 시스템은 State 패턴이 복잡한 조건문 없이 vehicle의 이용 가능 여부를 우아하게 처리하는 방법, 상속이 다형성 가격 책정을 지원하는 깔끔한 vehicle 계층 구조를 만드는 방법, 그리고 캡슐화가 전체 workflow에서 rental 데이터의 무결성을 보호하는 방법을 보여 줍니다.
직접 해보기
<?php
require_once 'RentalService.php';
require_once 'Customer.php';
// 입력 읽기
$fleetJson = trim(fgets(STDIN));
$customerJson = trim(fgets(STDIN));
$operationsJson = trim(fgets(STDIN));
// JSON 데이터 파싱
$fleetData = (array)json_decode($fleetJson, true);
$customerData = (array)json_decode($customerJson, true);
$operations = (array)json_decode($operationsJson, true);
// TODO: RentalService 인스턴스 생성
// TODO: 유형에 따라 모든 차량을 플릿에 추가:
// - "car" -> new Car(plate, brand, rate)
// - "motorcycle" -> new Motorcycle(plate, brand, rate)
// - "van" -> new Van(plate, brand, rate, mileage_rate)
// TODO: customerData에서 Customer 인스턴스 생성
// TODO: plate별로 활성 렌탈을 추적하는 배열 생성
$activeRentals = [];
// TODO: 각 작업을 처리하고 결과 출력:
// - "available": Print "Available vehicles: [count]"
// - "rent": 차량 대여, 성공 시 Rental 저장, 결과 출력
// - "complete": 렌탈 완료, 결과 출력
// - "maintenance": 유지보수 설정, 결과 출력
// - "status": "[plate]: [status]" 출력
// - "customer_stats": "[name]: [count] rentals, $[total] spent" 출력
foreach ($operations as $op) {
$operation = (array)$op;
$opType = $operation['op'];
// TODO: 각 작업 유형 처리
switch ($opType) {
case 'available':
// TODO: Print available vehicle count
break;
case 'rent':
// TODO: 차량 대여 및 결과 출력
break;
case 'complete':
// TODO: 대여 완료 및 결과 출력
break;
case 'maintenance':
// TODO: 유지보수 설정 및 결과 출력
break;
case 'status':
// TODO: 차량 상태 출력
break;
case 'customer_stats':
// TODO: 고객 통계 출력
break;
}
}
?>객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러