E-Learning Platform
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 88 of 91.
Challenge
EasyLet's build an E-Learning Platform that manages courses, students, and instructors. This comprehensive challenge brings together inheritance, interfaces, encapsulation, and design patterns into a cohesive system.
You'll organize your code across six files:
User.php— Create an abstractUserclass that serves as the base for both students and instructors. Use constructor promotion forid(int) andname(string), both public readonly. Include an abstract methodgetRole(): stringthat child classes must implement.Student.php— Include the User file. Create aStudentclass extendingUser. Students track their enrolled courses in a private array and their progress (percentage completed) for each course. Implement:getRole(): string— returns"Student"enrollInCourse(Course $course): string— enrolls the student if the course has capacity; returns success or failure messagegetEnrolledCourses(): array— returns the array of enrolled coursesupdateProgress(string $courseTitle, int $percent): void— sets progress for a course (0-100)getProgress(string $courseTitle): int— returns progress percentage, or 0 if not enrolled
Instructor.php— Include the User file. Create anInstructorclass extendingUser. Instructors can create and manage courses. Implement:getRole(): string— returns"Instructor"createCourse(string $title, int $capacity): Course— creates and returns a new Course with this instructor assigned
Course.php— Include the Instructor file. Create aCourseclass with constructor promotion fortitle(string, public readonly),instructor(Instructor, public readonly), andcapacity(int, private). Track enrolled students in a private array. Implement:getCapacity(): int— returns the maximum capacitygetEnrolledCount(): int— returns current enrollment counthasCapacity(): bool— returns true if more students can enrolladdStudent(Student $student): bool— adds student if capacity allows, returns success statusgetStudents(): array— returns enrolled students array
Platform.php— Include the Course and Student files. Create aPlatformclass that manages the entire system. Store courses and users in private arrays. Implement:addCourse(Course $course): void— adds a course to the platformfindCourse(string $title): ?Course— finds a course by titleenrollStudent(Student $student, string $courseTitle): string— enrolls a student in a course. Return"Course not found","Course is full", or"[name] enrolled in [title]"getCourseStats(string $title): string— returns"[title]: [enrolled]/[capacity] students"or"Course not found"
main.php— Include the Platform file. You'll receive three inputs: instructor data (JSON), courses to create (JSON), and operations to perform (JSON).Instructor JSON format:
{"id": 1, "name": "Dr. Smith"}Courses JSON format:
[{"title": "PHP Basics", "capacity": 2}, {"title": "OOP Mastery", "capacity": 3}]Operations JSON format:
[{"type": "enroll", "student_id": 1, "student_name": "Alice", "course": "PHP Basics"}, {"type": "progress", "student_id": 1, "course": "PHP Basics", "percent": 50}, {"type": "stats", "course": "PHP Basics"}]Create the platform, instructor, and all courses (using the instructor's
createCoursemethod). Add courses to the platform. Then process each operation:"enroll"— Create a new Student and enroll them; print the result fromenrollStudent()"progress"— Update student progress; print"[name] progress in [course]: [percent]%""stats"— Print the result fromgetCourseStats()
Keep track of created students by their ID so you can update their progress later. Print each operation's result on a new line.
This challenge demonstrates how inheritance creates a clean user hierarchy, encapsulation protects enrollment data, and the platform acts as a coordinator managing the relationships between courses, students, and instructors.
Try it yourself
<?php
require_once 'Platform.php';
// Read inputs
$instructorData = (array)json_decode(trim(fgets(STDIN)), true);
$coursesData = (array)json_decode(trim(fgets(STDIN)), true);
$operations = (array)json_decode(trim(fgets(STDIN)), true);
// TODO: Create the platform
// TODO: Create the instructor from instructorData
// TODO: Create all courses using the instructor's createCourse method
// and add them to the platform
// TODO: Keep track of created students by their ID
$students = [];
// TODO: Process each operation
foreach ($operations as $op) {
$operation = (array)$op;
// TODO: Handle "enroll" operation
// Create a new Student and enroll them
// Print the result from enrollStudent()
// TODO: Handle "progress" operation
// Update student progress
// Print "[name] progress in [course]: [percent]%"
// TODO: Handle "stats" operation
// Print the result from getCourseStats()
}
?>All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern