solophp/abstract-repository

An abstract repository implementation for PHP applications, providing a standardized way to interact with database tables using the Solo Query Builder.

v1.0.0 2025-04-15 10:06 UTC

This package is auto-updated.

Last update: 2025-04-15 10:07:17 UTC


README

Version License

An abstract repository implementation for PHP applications, providing a standardized way to interact with database tables using the Solo Query Builder.

Installation

composer require solophp/abstract-repository

Features

  • Unified Repository Pattern: Standardized interface for database operations
  • CRUD Operations: Complete set of Create, Read, Update, Delete methods
  • Filtering and Sorting: Flexible criteria-based querying with sorting options
  • Soft Delete Support: Optional soft deletion with restore capabilities
  • Pagination: Built-in support for paginated results
  • Record Synchronization: Efficient bulk operations for synchronizing datasets
  • Transaction Support: Atomic operations for data integrity

Basic Usage

Creating a Repository

<?php

namespace App\Repositories;

use Solo\AbstractRepository;
use Solo\QueryBuilder;

class UserRepository extends AbstractRepository
{
    // Optionally enable soft deletes
    protected bool $softDeletes = true;

    // Override primary key if not 'id'
    protected string $primaryKey = 'user_id';
    
    public function __construct(QueryBuilder $queryBuilder)
    {
        parent::__construct($queryBuilder, 'users');
    }
    
    // Add your custom repository methods here
    public function findActiveUsers(): array
    {
        return $this->selectBy(['status' => 'active']);
    }
}

Basic Operations

// Instantiate your repository
$userRepo = new UserRepository($queryBuilder);

// Select by ID
$user = $userRepo->selectById(123);

// Select all records
$allUsers = $userRepo->selectAll();

// Create a new record
$userId = $userRepo->insert([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'created_at' => date('Y-m-d H:i:s')
]);

// Update a record
$userRepo->update(123, [
    'name' => 'Jane Smith',
    'updated_at' => date('Y-m-d H:i:s')
]);

// Delete a record
$userRepo->deleteById(123);

Advanced Usage

Querying with Criteria

// Find records with criteria
$admins = $userRepo->selectBy([
    'role' => 'admin',
    'status' => 'active'
]);

// With ordering
$sortedAdmins = $userRepo->selectBy(
    ['role' => 'admin'],
    ['last_login' => 'DESC']
);

// With pagination
$paginatedUsers = $userRepo->selectBy(
    ['status' => 'active'],
    ['created_at' => 'DESC'],
    10,  // limit per page
    2    // page number
);

// Find first matching record
$firstAdmin = $userRepo->selectFirstBy(['role' => 'admin']);

Working with Soft Deletes

// Soft delete (if enabled)
$userRepo->deleteById(123);

// Force delete (bypasses soft delete)
$userRepo->forceDeleteById(123);

// Get soft-deleted records
$deletedUsers = $userRepo->selectDeleted();

// Restore a soft-deleted record
$userRepo->restoreById(123);

Record Existence Checks

// Check if record exists with the email
$exists = $userRepo->exists(['email' => 'john@example.com']);

// Check if another record exists with the same email (excluding current record)
$duplicateExists = $userRepo->existsExcluding(
    ['email' => 'john@example.com'],
    '123'
);

Bulk Operations

// Insert multiple records in a single transaction
$userIds = $userRepo->insertMultiple([
    ['name' => 'User 1', 'email' => 'user1@example.com'],
    ['name' => 'User 2', 'email' => 'user2@example.com'],
    ['name' => 'User 3', 'email' => 'user3@example.com']
]);

// Synchronize collections
// - Creates new records
// - Updates existing records
// - Deletes records not in the newUsers array
$userRepo->syncById($newUsers, $currentUsers);

Direct Database Access

// Get the underlying database instance for custom operations
$db = $userRepo->db();

// Perform custom transactions
$db->withTransaction(function() use ($userRepo) {
    // Multiple operations in a single transaction
    $userId = $userRepo->insert(['name' => 'New User']);
    $userRepo->update($userId, ['profile_created' => true]);
    // ...
});

Available Methods

Read Operations

Method Description
selectById(string|int $id): ?object Get a record by primary key
selectAll(): array Get all records
selectFirstBy(array $criteria, ?array $orderBy = null): ?object Get first record matching criteria
selectBy(array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $page = null): array Get records matching criteria
selectDeleted(): array Get soft-deleted records

Write Operations

Method Description
insert(array $data): string|false Insert a record
insertMultiple(array $records): array Insert multiple records
update(string|int $id, array $data): int Update a record
deleteById(string $id): int Delete a record (soft if enabled)
forceDeleteById(string $id): int Force delete a record
deleteBy(array $criteria): int Delete records matching criteria
restoreById(string|int $id): int Restore a soft-deleted record
syncById(array $newRecords, array $currentRecords): void Synchronize records

Utility Methods

Method Description
exists(array $criteria): bool Check if a record exists
existsExcluding(array $criteria, string $excludeId): bool Check if a record exists, excluding ID
db(): Database Get the database instance

Requirements

  • PHP 8.2 or higher
  • solophp/query-builder package

License

The MIT License (MIT). Please see License File for more information.