Skip to content

Instantly share code, notes, and snippets.

@MacDada
Last active April 9, 2022 21:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MacDada/e935a24da30db459e2b55711678631ac to your computer and use it in GitHub Desktop.
Save MacDada/e935a24da30db459e2b55711678631ac to your computer and use it in GitHub Desktop.
PHP: Use Case architecture example
<?php
class ShowBlogPostsController
{
/**
* @param ShowBlogPostUseCase
**/
private $useCase;
/**
* @param TemplateEngine
**/
private $templateEngine;
public function __construct(ShowBlogPostUseCase $useCase, TemplateEngine $templateEngine)
{
$this->useCase = $useCase;
$this->templateEngine = $templateEngine;
}
public function showBlogPostsAction(HttpRequest $httpRequest)
{
$useCaseRequest = new ShowBlogPostsRequest();
$useCaseRequest->page = $httpRequest->query->get('page');
$useCaseRequest->categoryName = $httpRequest->query->get('category');
$useCaseResponse = $this->useCase->handle($useCaseRequest);
$content = $this->templateEngine->render('blog/posts', [
'posts' => $useCaseResponse->posts,
'all_posts_count' => $useCaseResponse->allPostsCount,
'categories' => $useCaseResponse->categories,
]);
return new HttpResponse($content);
}
}
<?php
class ShowBlogPostsRequest
{
/**
* @param int
*/
public $page;
/**
* @param string
**/
public $categoryName;
}
<?php
// simple DTO, but one could create getters instead of public properties ofc
class ShowBlogPostsResponse
{
/**
* @param Post[]
**/
public $posts;
/**
* @param int
**/
public $allPostsCount;
/**
* @param PostCategory[]
**/
public $categories;
}
<?php
class ShowBlogPostsUseCase
{
/**
* @param PostRepository
**/
private $postRepository;
/**
* @param CategoryRepository
**/
private $categoryRepository;
/**
* @param int
**/
private $postsLimit;
public function __construct(
PostRepository $postRepository,
CategoryRepository $categoryRepository,
$postsLimit
) {
$this->postRepository = $postRepository;
$this->categoryRepository = $categoryRepository;
$this->postsLimit = $postsLimit;
}
public function handle(ShowBlogPostsRequest $request)
{
$category = $this->categoryRepository->findOneByName($request->categoryName);
$posts = $this->postRepository->findByCategoryAndPage(
$category,
$request->page,
$this->limit
);
$response = new ShowBlogPostsResponse();
$response->posts = $posts;
$response->allPostsCount = $this->postRepository->count();
$response->categories = $this->categoriesRepository->findAll();
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment