<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
adobrovolsky97 / laravel-repository-service-pattern example snippets
namespace App;
class Post extends Model {
protected $fillable = [
'title',
'author',
...
];
...
}
namespace App;
use Adobrovolsky97\LaravelRepositoryServicePattern\Repositories\BaseRepository;
class PostRepository extends BaseRepository implements PostRepositoryInterface {
/**
* Specify Model class name
*
* @return string
*/
protected function getModelClass(): string
{
return Post::class;
}
}
namespace App;
use Adobrovolsky97\LaravelRepositoryServicePattern\Repositories\BaseRepository;
class PostService extends BaseCrudService implements PostServiceInerface {
/**
* Specify Repository class name
*
* @return string
*/
protected function getRepositoryClass(): string
{
return PostRepositoryInteface::class;
}
}
class AppServiceProvider extends ServiceProvider {
/**
* Specify Repository class name
*
* @return string
*/
public function register(): void
{
$this->app->singleton(PostRepositoryInterface::class, PostRepository::class);
$this->app->singleton(PostServiceInterface::class, PostService::class);
}
}
namespace App\Http\Controllers;
use App\PostServiceInterface;
class PostsController extends Controller {
/**
* @var PostServiceInterface
*/
protected PostServiceInterface $service;
public function __construct(PostServiceInterface $service)
{
$this->service = $service;
}
....
}
public function index(SearchRequest $request): AnonymousResourceCollection
{
return PostResource::collection($this->service->withTrashed()->getAllPaginated($request->validated(), 25));
}
public function show(int $postId): PostResource
{
return PostResource::make($this->service->findOrFail($postId));
}
public function store(StoreRequest $request): PostResource
{
return PostResource::make($this->service->create($request->validated()));
}
public function update(Post $post, UpdateRequest $request): PostResource
{
return PostResource::make($this->service->update($post, $request->validated()));
}
public function destroy(Post $post): JsonResponse
{
$this->service->delete($post);
// Or
$this->service->softDelete($post);
return Response::json(null, 204);
}
public function restore(Post $deletedPost): PostResource
{
$this->service->restore($deletedPost);
return PostResource::make($deletedPost->refresh());
}
$posts = $this->service->getAll();
// Those are equivalent
$posts = $this->service->withoutTrashed()->getAll();