Bird
Raised Fist0
PHPprogramming~20 mins

Repository pattern in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Repository Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Repository pattern example?

Consider this PHP code using a simple repository pattern to fetch user data.

<?php
interface UserRepository {
    public function findUserById(int $id): ?array;
}

class InMemoryUserRepository implements UserRepository {
    private array $users = [
        1 => ['id' => 1, 'name' => 'Alice'],
        2 => ['id' => 2, 'name' => 'Bob']
    ];

    public function findUserById(int $id): ?array {
        return $this->users[$id] ?? null;
    }
}

$repo = new InMemoryUserRepository();
$user = $repo->findUserById(2);
echo $user['name'] ?? 'Not found';
?>

What will this code print?

PHP
<?php
interface UserRepository {
    public function findUserById(int $id): ?array;
}

class InMemoryUserRepository implements UserRepository {
    private array $users = [
        1 => ['id' => 1, 'name' => 'Alice'],
        2 => ['id' => 2, 'name' => 'Bob']
    ];

    public function findUserById(int $id): ?array {
        return $this->users[$id] ?? null;
    }
}

$repo = new InMemoryUserRepository();
$user = $repo->findUserById(2);
echo $user['name'] ?? 'Not found';
?>
ANot found
BBob
CAlice
DFatal error: Uncaught Error: Undefined array key 2
Attempts:
2 left
💡 Hint

Look at the user ID requested and the data stored in the repository.

🧠 Conceptual
intermediate
1:30remaining
Which statement best describes the Repository pattern?

Choose the best description of the Repository pattern in software design.

AIt separates data access logic from business logic by providing a collection-like interface to access domain objects.
BIt is a pattern to directly connect the UI with the database for faster queries.
CIt is a design pattern that forces all data to be stored in memory for quick access.
DIt is a pattern that replaces the need for any database or external storage.
Attempts:
2 left
💡 Hint

Think about how the Repository pattern helps organize code related to data.

🔧 Debug
advanced
2:00remaining
What error does this Repository pattern code produce?

Examine this PHP code snippet using a repository pattern:

<?php
class UserRepository {
    private array $users = [];

    public function findUserById(int $id): array {
        return $this->users[$id];
    }
}

$repo = new UserRepository();
$user = $repo->findUserById(1);
echo $user['name'];
?>

What error will this code cause when run?

PHP
<?php
class UserRepository {
    private array $users = [];

    public function findUserById(int $id): array {
        return $this->users[$id];
    }
}

$repo = new UserRepository();
$user = $repo->findUserById(1);
echo $user['name'];
?>
ANo error, prints empty string
BNotice: Undefined variable: users
CParse error: syntax error, unexpected 'echo' (T_ECHO)
DFatal error: Uncaught Error: Undefined array key 1
Attempts:
2 left
💡 Hint

Check what data is stored in the repository before accessing it.

📝 Syntax
advanced
2:00remaining
Which option correctly implements a Repository interface in PHP?

Given this interface:

<?php
interface ProductRepository {
    public function findProductById(int $id): ?array;
}
?>

Which class correctly implements this interface?

A
class MyRepo implements ProductRepository {
    public function findProductById(int $id): array {
        return [];
    }
}
B
class MyRepo implements ProductRepository {
    public function findProductById($id) {
        return [];
    }
}
C
class MyRepo implements ProductRepository {
    public function findProductById(int $id): ?array {
        return null;
    }
}
D
class MyRepo implements ProductRepository {
    public function findProductById(int $id) {
        return null;
    }
}
Attempts:
2 left
💡 Hint

Check method signature matches exactly including return type and parameter types.

🚀 Application
expert
2:30remaining
How many items are in the repository after these operations?

Consider this PHP repository class and usage:

<?php
class ItemRepository {
    private array $items = [];

    public function addItem(array $item): void {
        $this->items[$item['id']] = $item;
    }

    public function removeItem(int $id): void {
        unset($this->items[$id]);
    }

    public function getAllItems(): array {
        return array_values($this->items);
    }
}

$repo = new ItemRepository();
$repo->addItem(['id' => 1, 'name' => 'Pen']);
$repo->addItem(['id' => 2, 'name' => 'Pencil']);
$repo->addItem(['id' => 3, 'name' => 'Eraser']);
$repo->removeItem(2);
$repo->addItem(['id' => 2, 'name' => 'Marker']);
$items = $repo->getAllItems();
echo count($items);
?>

What number will be printed?

PHP
<?php
class ItemRepository {
    private array $items = [];

    public function addItem(array $item): void {
        $this->items[$item['id']] = $item;
    }

    public function removeItem(int $id): void {
        unset($this->items[$id]);
    }

    public function getAllItems(): array {
        return array_values($this->items);
    }
}

$repo = new ItemRepository();
$repo->addItem(['id' => 1, 'name' => 'Pen']);
$repo->addItem(['id' => 2, 'name' => 'Pencil']);
$repo->addItem(['id' => 3, 'name' => 'Eraser']);
$repo->removeItem(2);
$repo->addItem(['id' => 2, 'name' => 'Marker']);
$items = $repo->getAllItems();
echo count($items);
?>
A3
B2
C1
D4
Attempts:
2 left
💡 Hint

Count how many unique items remain after adding and removing by ID.

Practice

(1/5)
1. What is the main purpose of the Repository pattern in PHP?
easy
A. To separate data access logic from business logic
B. To directly connect the database with the user interface
C. To write all code inside a single class
D. To avoid using interfaces in the code

Solution

  1. Step 1: Understand the role of Repository pattern

    The Repository pattern is designed to separate how data is accessed from how the business logic works.
  2. Step 2: Identify the correct purpose

    Separating data access from business logic makes code cleaner and easier to maintain.
  3. Final Answer:

    To separate data access logic from business logic -> Option A
  4. Quick Check:

    Repository pattern = separation of concerns [OK]
Hint: Remember: Repository separates data logic from business logic [OK]
Common Mistakes:
  • Thinking Repository connects UI directly to database
  • Believing all code should be in one class
  • Ignoring the use of interfaces
2. Which of the following is the correct way to declare a Repository interface in PHP?
easy
A. UserRepository interface { public function findUser(int $id); }
B. class UserRepository { public function findUser(int $id); }
C. interface UserRepository { function findUser; }
D. interface UserRepository { public function findUser(int $id); }

Solution

  1. Step 1: Recall PHP interface syntax

    Interfaces use the keyword interface followed by method declarations with parentheses and types.
  2. Step 2: Check each option

    interface UserRepository { public function findUser(int $id); } correctly declares an interface with a method having a typed parameter. class UserRepository { public function findUser(int $id); } uses class instead of interface. interface UserRepository { function findUser; } misses parentheses. UserRepository interface { public function findUser(int $id); } has wrong syntax order.
  3. Final Answer:

    interface UserRepository { public function findUser(int $id); } -> Option D
  4. Quick Check:

    Interface syntax = interface UserRepository { public function findUser(int $id); } [OK]
Hint: Interfaces use 'interface' keyword and method signatures with parentheses [OK]
Common Mistakes:
  • Using 'class' instead of 'interface'
  • Omitting parentheses in method declaration
  • Wrong keyword order in interface declaration
3. Given the following PHP code, what will be the output?
interface UserRepository {
    public function findUser(int $id);
}

class UserRepo implements UserRepository {
    public function findUser(int $id) {
        return "User_" . $id;
    }
}

$repo = new UserRepo();
echo $repo->findUser(5);
medium
A. 5
B. User_5
C. UserRepo
D. Error: Interface method not implemented

Solution

  1. Step 1: Understand interface and class implementation

    The class UserRepo implements UserRepository and defines the method findUser that returns "User_" concatenated with the id.
  2. Step 2: Trace the method call

    Calling $repo->findUser(5) returns "User_5" which is then printed.
  3. Final Answer:

    User_5 -> Option B
  4. Quick Check:

    Method returns 'User_' + id = User_5 [OK]
Hint: Look for string concatenation in method return [OK]
Common Mistakes:
  • Expecting just the number 5 as output
  • Confusing class name with output
  • Thinking interface causes error if implemented correctly
4. Identify the error in this PHP Repository implementation:
interface ProductRepository {
    public function getProduct(int $id);
}

class ProductRepo implements ProductRepository {
    public function getProduct() {
        return "Product";
    }
}
medium
A. Class name should be ProductRepository, not ProductRepo
B. Interface keyword is misspelled
C. Method getProduct() missing parameter in class implementation
D. Return type is missing in interface method

Solution

  1. Step 1: Compare interface and class method signatures

    The interface method getProduct requires an int $id parameter, but the class method has no parameters.
  2. Step 2: Understand PHP interface implementation rules

    When implementing an interface, method signatures must match exactly, including parameters.
  3. Final Answer:

    Method getProduct() missing parameter in class implementation -> Option C
  4. Quick Check:

    Method signatures must match [OK]
Hint: Check method parameters match interface exactly [OK]
Common Mistakes:
  • Ignoring parameter mismatch
  • Thinking class name must match interface name
  • Assuming return type is mandatory in interface
5. You want to create a flexible Repository pattern for managing users and products. Which design approach best supports adding new data types without changing existing code?
hard
A. Create separate interfaces like UserRepository and ProductRepository, then implement them in separate classes
B. Write one big class handling all data types with many methods
C. Use global functions to access data directly
D. Store all data in arrays inside a single class without interfaces

Solution

  1. Step 1: Understand flexibility in Repository pattern

    Using separate interfaces and classes for each data type allows adding new repositories without changing existing ones.
  2. Step 2: Evaluate options for maintainability

    Create separate interfaces like UserRepository and ProductRepository, then implement them in separate classes supports open/closed principle: open for extension, closed for modification. Other options mix concerns or lack structure.
  3. Final Answer:

    Create separate interfaces like UserRepository and ProductRepository, then implement them in separate classes -> Option A
  4. Quick Check:

    Separate interfaces = flexible extension [OK]
Hint: Use separate interfaces and classes for each data type [OK]
Common Mistakes:
  • Putting all logic in one big class
  • Using global functions instead of classes
  • Avoiding interfaces reduces flexibility
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard