PHP code example of jdikasa / laravel-repository-pattern
1. Go to this page and download the library: Download jdikasa/laravel-repository-pattern library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
jdikasa / laravel-repository-pattern example snippets
// app/Repositories/PostRepository.php
class PostRepository extends BaseRepository
{
public function model(): string
{
return Post::class;
}
public function getPublishedPosts()
{
return $this->model->where('status', 'published')->get();
}
}
// app/Services/PostService.php
class PostService
{
public function __construct(
private PostRepository $postRepository
) {}
public function createPost(array $data): Post
{
return $this->postRepository->create($data);
}
}
// app/Http/Controllers/PostController.php
class PostController extends Controller
{
public function __construct(
private PostService $postService,
private PostTransformer $postTransformer
) {}
public function store(StorePostRequest $request)
{
$post = $this->postService->createPost($request->validated());
return response()->json([
'data' => $this->postTransformer->transform($post)
], 201);
}
}