Skip to content

Commit 2fa0a69

Browse files
authored
Merge pull request #6 from longaodai/develop
Release
2 parents 9d0556f + 9719726 commit 2fa0a69

File tree

6 files changed

+145
-151
lines changed

6 files changed

+145
-151
lines changed

README.md

Lines changed: 63 additions & 119 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@
44
[![Total Downloads](https://img.shields.io/packagist/dt/longaodai/laravel-repository.svg?style=flat-square)](https://packagist.org/packages/longaodai/laravel-repository)
55
[![License](https://img.shields.io/packagist/l/longaodai/laravel-repository.svg?style=flat-square)](https://packagist.org/packages/longaodai/laravel-repository)
66

7-
A comprehensive Laravel package that implements the Repository and Service Layer design patterns, providing a clean and
8-
maintainable way to interact with your Eloquent models. This package promotes separation of concerns, making your code
9-
more testable, organized, and following SOLID principles.
7+
A comprehensive Laravel package that implements the **Repository** and **Service Layer** design patterns, providing a clean and maintainable way to interact with your Eloquent models. This package promotes separation of concerns, making your code more testable, organized, and following SOLID principles.
108

119
## Features
1210

@@ -17,14 +15,10 @@ more testable, organized, and following SOLID principles.
1715
- **Performance Optimized** - Built with Laravel best practices
1816
- **Rich Query Methods** - Comprehensive set of query methods out of the box
1917

20-
## Table of Contents
18+
## Requirements
2119

22-
- [Installation](#installation)
23-
- [Configuration](#configuration)
24-
- [Quick Start](#quick-start)
25-
- [Available Methods](#available-methods)
26-
- [Best Practices](#best-practices)
27-
- [License](#license)
20+
- PHP >= 8.0
21+
- Laravel >= 9.0
2822

2923
## Installation
3024

@@ -34,80 +28,52 @@ You can install the package via Composer:
3428
composer require longaodai/laravel-repository
3529
```
3630

37-
## Configuration
38-
3931
Publish the configuration file:
4032

4133
```bash
4234
php artisan vendor:publish --tag=laravel-repository
4335
```
4436

45-
This will create a `config/repository.php` file where you can customize.
37+
This will create a `config/repository.php` file where you can customize package settings.
4638

4739
## Quick Start
4840

49-
### 1. Generate Repository and Service
50-
5141
Generate a complete repository and service for your model:
5242

5343
```bash
5444
php artisan make:repository User
5545
```
5646

57-
**Options:**
58-
59-
- `--model=ModelName` : Specify the model class name
60-
- `--force` : Overwrite existing files
61-
**Result:**
47+
### Available Options:
48+
- `--model=ModelName`: Specify the model class name
49+
- `--force`: Overwrite existing files
6250

51+
### Generated Files:
6352
```
6453
Repository Interface ........... App\Repositories\User\UserRepositoryInterface
65-
Repository Implementation ...... App\Repositories\User\UserEloquentRepository
66-
Service Interface .............. App\Services\User\UserServiceInterface
54+
Repository Implementation ...... App\Repositories\User\UserEloquentRepository
55+
Service Interface .............. App\Services\User\UserServiceInterface
6756
Service Implementation ......... App\Services\User\UserService
6857
```
6958

70-
### 2. Register Service Providers
59+
### Register Service Providers
7160

72-
Add the generated service providers to your `bootstrap/providers.php` (only one in the first time):
61+
Add the generated service providers to your `bootstrap/providers.php` (only once after running the first make repository command):
7362

7463
```php
7564
<?php
7665
return [
7766
App\Providers\AppServiceProvider::class,
7867
// ... other providers
7968

80-
// Add these lines
69+
// Add these lines
8170
App\Providers\RepositoryServiceProvider::class,
8271
App\Providers\InternalServiceProvider::class,
8372
];
8473
```
8574

86-
### 3. Usage
87-
88-
### Generating Repositories
89-
90-
The package provides an Artisan command to generate repositories and services:
91-
92-
```bash
93-
# Generate repository for existing model
94-
php artisan make:repository User
95-
96-
# Generate repository and specify model
97-
php artisan make:repository User --model=User
98-
99-
# Force overwrite existing files
100-
php artisan make:repository User --force
101-
```
102-
103-
This generates four files:
104-
105-
1. `UserRepositoryInterface` - Repository contract
106-
2. `UserEloquentRepository` - Eloquent implementation
107-
3. `UserServiceInterface` - Service contract
108-
4. `UserService` - Service implementation
109-
110-
### Use in Controllers
75+
## Usage
76+
### Controller Integration
11177

11278
Inject and use the service in your controllers:
11379

@@ -198,7 +164,7 @@ class UserController extends Controller
198164
}
199165
```
200166

201-
#### Custom Repository Methods
167+
### Custom Repository Methods
202168

203169
Add custom methods to your repository:
204170

@@ -221,20 +187,21 @@ class UserEloquentRepository extends BaseRepository implements UserRepositoryInt
221187
* Hook for filtering queries.
222188
*
223189
* @param RepositoryResponse $params
190+
*
224191
* @return static
225192
*/
226193
protected function filter(RepositoryResponse $params): static
227194
{
228195
if (!empty($params->get('id'))) {
229-
$this->method('where', 'id', $params->get('id'));
196+
$this->method('where', $this->table . '.id', $params->get('id'));
230197
}
231198

232199
if (!empty($params->get('name'))) {
233-
$this->method('where', 'name', $params->get('name'));
200+
$this->method('where', $this->table . '.name', $params->get('name'));
234201
}
235202

236203
if (!empty($params->get('status'))) {
237-
$this->method('where', 'status', $params->get('status'));
204+
$this->method('where', $this->table . '.status', $params->get('status'));
238205
}
239206

240207
if (!empty($params->option('with_post'))) {
@@ -247,23 +214,24 @@ class UserEloquentRepository extends BaseRepository implements UserRepositoryInt
247214
}
248215

249216
/**
250-
* Hook for masking data before update.
217+
* Hook for filtering update.
251218
*
252219
* @param RepositoryResponse $params
220+
*
253221
* @return static
254222
*/
255223
protected function mask(RepositoryResponse $params): static
256224
{
257225
if (!empty($params->option('id'))) {
258-
$this->method('where', 'id', $params->option('id'));
226+
$this->method('where', $this->table . '.id', $params->option('id'));
259227
}
260228

261229
return parent::mask($params);
262230
}
263231
}
264232
```
265233

266-
#### Service Layer Business Logic
234+
### Service Layer Business Logic
267235

268236
Implement complex business logic in services:
269237

@@ -278,11 +246,9 @@ use Illuminate\Support\Facades\DB;
278246

279247
class UserService implements UserServiceInterface
280248
{
281-
protected $userRepository;
282-
283-
public function __construct(UserRepositoryInterface $userRepository)
249+
public function __construct(UserRepositoryInterface $repository)
284250
{
285-
$this->userRepository = $userRepository;
251+
$this->userRepository = $repository;
286252
}
287253

288254
/**
@@ -293,11 +259,13 @@ class UserService implements UserServiceInterface
293259
return DB::transaction(function () use ($userData) {
294260
// Create user
295261
$user = $this->userRepository->create($userData);
262+
296263
// Send welcome notification
297264
$user->notify(new WelcomeNotification());
265+
298266
// Log user creation
299267
logger('New user created', ['user_id' => $user->id]);
300-
268+
301269
return $user;
302270
});
303271
}
@@ -311,7 +279,6 @@ class UserService implements UserServiceInterface
311279
[
312280
'status' => $data['status'],
313281
], [
314-
'limit' => 10,
315282
'with_post' => true,
316283
]
317284
);
@@ -323,18 +290,20 @@ class UserService implements UserServiceInterface
323290

324291
The base repository provides these methods out of the box:
325292

326-
| Method | Description | Example |
327-
|--------------------------------------|---------------------------------|---------------------------------------------------------------------------------|
328-
| `all()` | Get all records | `$service->all()` |
329-
| `getList($params)` | Get paginated list with filters | `$service->getList(['per_page' => 10])` |
330-
| `find($conditions)` | Find by id | `$service->find(['id' => 1])` |
331-
| `first($conditions)` | Get first record by conditions | `$service->first(['status' => 'active'])` |
332-
| `create($data)` | Create new record | `$service->create(['name' => 'John'])` |
333-
| `update($data, $conditions)` | Update records | `$service->update(['name' => 'Jane'], ['id' => 1])` |
334-
| `updateOrCreate($conditions, $data)` | Update or create record | `$service->updateOrCreate(['email' => 'test@example.com'], ['name' => 'Test'])` |
335-
| `destroy($conditions)` | Delete records | `$service->destroy(['id' => 1])` |
293+
| Method | Description | Example |
294+
|--------|--------------------------------|-----------------------------------------------------|
295+
| `all()` | Get all records | `$service->all()` |
296+
| `getList($params)` | Get paginated list with filters | `$service->getList(['per_page' => 10])` |
297+
| `find($conditions)` | Find by id | `$service->find(['id' => 1])` |
298+
| `first($conditions)` | Get first record by conditions | `$service->first(['status' => 'active'])` |
299+
| `create($data)` | Create new record | `$service->create(['name' => 'John'])` |
300+
| `update($data, $conditions)` | Update records | `$service->update(['name' => 'Jane'], ['id' => 1])` |
301+
| `updateOrCreate($conditions, $data)` | Update or create record | `$service->updateOrCreate(['name' => 'Test'], ['email' => 'test@example.com'])` |
302+
| `destroy($conditions)` | Delete records | `$service->destroy(['id' => 1])` |
303+
304+
## Method Examples
336305

337-
### Advanced Query Examples
306+
### Retrieving Data
338307

339308
```php
340309
// Get all users
@@ -353,27 +322,38 @@ $user = $userService->find(['id' => 1]);
353322
// Get first user with conditions
354323
$activeUser = $userService->first(['status' => 'active']);
355324
$user = $userService->first(['email' => 'user@example.com']);
325+
```
326+
327+
### Creating Data
356328

329+
```php
357330
// Create new user
358331
$newUser = $userService->create(collect([
359332
'name' => 'John Doe',
360333
'email' => 'john@example.com',
361334
'password' => bcrypt('password123'),
362335
'status' => 'active'
363336
]));
337+
```
364338

339+
### Updating Data
340+
341+
```php
365342
// Update user
366343
$updatedUser = $userService->update([
367-
'name' => 'John Smith',
368-
'updated_at' => now()
369-
], ['id' => 1]);
344+
'name' => 'John Smith', // data to update
345+
], ['id' => 1]); // conditions
370346

371347
// Update or create user
372348
$user = $userService->updateOrCreate(
373-
collect(['email' => 'jane@example.com']), // conditions
374349
collect(['name' => 'Jane Doe', 'status' => 'active']) // data to update/create
350+
collect(['email' => 'jane@example.com']), // conditions
375351
);
352+
```
376353

354+
### Deleting Data
355+
356+
```php
377357
// Delete user
378358
$deleted = $userService->destroy(['id' => 1]);
379359

@@ -383,9 +363,7 @@ $deleted = $userService->destroy(['status' => 'inactive']);
383363

384364
## Best Practices
385365

386-
### 1. Keep Controllers Thin
387-
388-
Move business logic to services, not controllers:
366+
### Move Business Logic to Services
389367

390368
```php
391369
// ❌ Bad - Logic in controller
@@ -396,9 +374,9 @@ public function store(Request $request)
396374
'email' => $request->email,
397375
'password' => bcrypt($request->password),
398376
]);
399-
377+
400378
$user->notify(new WelcomeNotification());
401-
379+
402380
return response()->json($user);
403381
}
404382

@@ -411,9 +389,7 @@ public function store(Request $request)
411389
}
412390
```
413391

414-
### 2. Use Type Hinting
415-
416-
Always use interface type hinting:
392+
### Always Use Interface Type Hinting
417393

418394
```php
419395
// ✅ Good
@@ -422,40 +398,12 @@ public function __construct(UserServiceInterface $userService)
422398
$this->userService = $userService;
423399
}
424400

425-
// ❌ Bad
401+
// ❌ Bad
426402
public function __construct(UserService $userService)
427403
{
428404
$this->userService = $userService;
429405
}
430406
```
431-
432-
### 3. Handle Exceptions Properly
433-
434-
Implement proper exception handling:
435-
436-
```php
437-
public function findUser($id)
438-
{
439-
try {
440-
$user = $this->userService->find(['id' => $id]);
441-
442-
if (!$user) {
443-
throw new RepositoryFailureHandlingException('User not found');
444-
}
445-
446-
return $user;
447-
} catch (Exception $e) {
448-
logger()->error('Error finding user', ['id' => $id, 'error' => $e->getMessage()]);
449-
throw $e;
450-
}
451-
}
452-
```
453-
454-
## Requirements
455-
456-
- PHP >= 8.0
457-
- Laravel >= 9.0
458-
459407
## Security
460408

461409
If you discover any security-related issues, please email vochilong.work@gmail.com instead of using the issue tracker.
@@ -475,7 +423,3 @@ If you find this package helpful, please consider:
475423
- Reporting any bugs you encounter
476424
- Suggesting new features
477425
- Improving documentation
478-
479-
For questions and support, please use
480-
the [GitHub Discussions](https://github.com/longaodai/laravel-repository/discussions) or create
481-
an [issue](https://github.com/longaodai/laravel-repository/issues).

0 commit comments

Comments
 (0)