Suggested level: Middle
Task Overview: Building a Simple User Management System
The challenge is divided into three steps, each increasing in complexity. The goal is to evaluate problem-solving skills, OOP understanding, and ability to refactor code.
Basic Functionality (Easy)
Task: Write a PHP function that stores user data in an array and retrieves user information by ID.
Requirements:
- A function
addUser(string $name, int $age): intthat adds a user and returns a unique ID. - A function
getUser(int $id): ?arraythat retrieves user details. - Data should be stored in-memory (simple array).
Example usage:
$id = addUser('Alice', 30);
$user = getUser($id);
// Output: ['id' => 1, 'name' => 'Alice', 'age' => 30]Expected skills and knowledge:
- Basic PHP skills
- Understanding of arrays and functions
- Handling of IDs and null values
Introduce OOP (Intermediate)
Task: Refactor the code into a UserManager class that follows OOP principles.
Requirements:
- Create a UserManager class.
- Use private properties for user storage.
- Implement the methods as class methods.
Example usage:
$manager = new UserManager();
$id = $manager->addUser('Bob', 25);
$user = $manager->getUser($id);Expected skills and knowledge:
- Object-oriented programming (OOP)
- Encapsulation & class structure
- Proper method design
Advanced - Implement Dependency Injection & Refactoring (Complex)
Task:
Refactor the UserManager class to:
- Use Dependency Injection for user storage (e.g., database or file-based storage).
- Introduce an interface for different storage implementations.
- Implement at least one concrete storage class (e.g., ArrayStorage).
Requirements:
- Define a UserStorageInterface with addUser() and getUser().
- Implement ArrayStorage as an example.
- Modify UserManager to use the storage via Dependency Injection.
Example usage:
$storage = new ArrayStorage();
$manager = new UserManager($storage);
$id = $manager->addUser('Charlie', 40);
$user = $manager->getUser($id);Expected skills and knowledge:
- Understanding of Dependency Injection
- Use of Interfaces & SOLID principles
- Ability to refactor and write maintainable code
Bonus Challenge (if time allows)
- Add a FileStorage class that persists user data to a JSON file.
- Implement error handling for missing users.