0
0
PHPprogramming~5 mins

Repository pattern in PHP

Choose your learning style9 modes available
Introduction

The Repository pattern helps you organize how your app talks to data storage. It keeps data access code separate from the rest of your app.

When you want to keep your database code separate from your business logic.
When you plan to switch data sources later without changing your app code.
When you want to write cleaner, easier-to-test code for data access.
When multiple parts of your app need to get or save data in the same way.
When you want to hide complex database queries behind simple methods.
Syntax
PHP
<?php
interface UserRepository {
    public function findById(int $id);
    public function save(User $user);
}

class UserRepositoryImpl implements UserRepository {
    public function findById(int $id) {
        // code to get user from database
    }
    public function save(User $user) {
        // code to save user to database
    }
}

The interface defines what methods the repository must have.

The implementation contains the actual code to get or save data.

Examples
This example shows a repository for products with methods to get all products or find one by name.
PHP
<?php
interface ProductRepository {
    public function findAll();
    public function findByName(string $name);
}

class ProductRepositoryImpl implements ProductRepository {
    public function findAll() {
        // return all products
    }
    public function findByName(string $name) {
        // return product by name
    }
}
This example shows a repository for orders with methods to find orders by user and save an order.
PHP
<?php
interface OrderRepository {
    public function findByUserId(int $userId);
    public function save(Order $order);
}

class OrderRepositoryImpl implements OrderRepository {
    public function findByUserId(int $userId) {
        // get orders for a user
    }
    public function save(Order $order) {
        // save order
    }
}
Sample Program

This program shows a simple User repository using an array to store users. It saves users and finds them by ID.

PHP
<?php
// Simple User class
class User {
    public int $id;
    public string $name;

    public function __construct(int $id, string $name) {
        $this->id = $id;
        $this->name = $name;
    }
}

// Repository interface
interface UserRepository {
    public function findById(int $id): ?User;
    public function save(User $user): void;
}

// Implementation using an array as data storage
class UserRepositoryImpl implements UserRepository {
    private array $users = [];

    public function findById(int $id): ?User {
        foreach ($this->users as $user) {
            if ($user->id === $id) {
                return $user;
            }
        }
        return null;
    }

    public function save(User $user): void {
        // Replace user if exists, else add
        foreach ($this->users as $index => $existingUser) {
            if ($existingUser->id === $user->id) {
                $this->users[$index] = $user;
                return;
            }
        }
        $this->users[] = $user;
    }
}

// Using the repository
$repo = new UserRepositoryImpl();

// Save some users
$repo->save(new User(1, "Alice"));
$repo->save(new User(2, "Bob"));

// Find user by id
$user = $repo->findById(1);
if ($user !== null) {
    echo "Found user: " . $user->name . "\n";
} else {
    echo "User not found\n";
}

// Try to find a user that does not exist
$user = $repo->findById(3);
if ($user !== null) {
    echo "Found user: " . $user->name . "\n";
} else {
    echo "User not found\n";
}
OutputSuccess
Important Notes

The Repository pattern helps you change the data source later without changing your app code.

Use interfaces to define repository methods so you can swap implementations easily.

Keep repository methods simple and focused on data access only.

Summary

The Repository pattern separates data access from business logic.

It uses interfaces and classes to organize how data is fetched and saved.

This makes your code cleaner, easier to test, and flexible to change.