0
0
PHPprogramming~5 mins

Repository pattern in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Repository pattern
O(n)
Understanding Time Complexity

When using the Repository pattern, it's important to understand how the time it takes to get data changes as the data grows.

We want to know how the number of operations grows when fetching or saving many items.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class UserRepository {
    private array $users = [];

    public function addUser(array $user): void {
        $this->users[] = $user;
    }

    public function findUserByEmail(string $email): ?array {
        foreach ($this->users as $user) {
            if ($user['email'] === $email) {
                return $user;
            }
        }
        return null;
    }
}
    

This code stores users in an array and searches for a user by email using a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the users array to find a matching email.
  • How many times: Up to once for each user in the array until a match is found or all checked.
How Execution Grows With Input

As the number of users grows, the search takes longer because it may check more users.

Input Size (n)Approx. Operations
10Up to 10 checks
100Up to 100 checks
1000Up to 1000 checks

Pattern observation: The number of checks grows roughly in direct proportion to the number of users.

Final Time Complexity

Time Complexity: O(n)

This means the time to find a user grows linearly with the number of users stored.

Common Mistake

[X] Wrong: "Searching in the repository is always fast and constant time."

[OK] Correct: Because the repository uses a simple array and loops through it, the search time grows as more users are added.

Interview Connect

Understanding how data retrieval time grows helps you explain design choices and shows you can think about efficiency in real projects.

Self-Check

"What if we changed the users storage from an array to a hash map keyed by email? How would the time complexity change?"