Skip to content

Instantly share code, notes, and snippets.

@patoui
Last active October 14, 2021 12:39
Show Gist options
  • Save patoui/55274fc691cbbf190bcb53ccb7f32c6b to your computer and use it in GitHub Desktop.
Save patoui/55274fc691cbbf190bcb53ccb7f32c6b to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
/**
* src/
* Domain/
* Entity/
* Factory/
* Repository/ // repository interfaces
* Service/
* Persistence/
* Repository/ // concrete repositories
* Infra/
* Http/
* Controller/
* Helper/
* ViewModel/
*/
// src/Domain/Repository
interface UserRepositoryInterface
{
public function getAll(): UserList;
}
// src/Domain/Repository
interface AnalyticsRepositoryInterface
{
public function getUserCount(): int;
public function getActiveUserCount(): int;
public function getNewUserCount(): int;
}
// src/Infra/Http/ViewModel
final class UserListViewModel
{
private UserRepositoryInterface $user_repository;
private AnalyticsRepositoryInterface $analytics_repository;
public function __construct(
UserRepositoryInterface $user_repository,
AnalyticsRepositoryInterface $analytics_repository
) {
$this->user_repository = $user_repository;
$this->analytics_repository = $analytics_repository;
}
public function fetch(): array
{
return [
'users' => $this->user_repository->getAll(),
'user_count' => $this->analytics_repository->getUserCount(),
'user_active_count' => $this->analytics_repository->getActiveUserCount(),
'user_new_count' => $this->analytics_repository->getNewUserCount(),
];
}
}
// src/Infra/Http/Helper
final class JsonResponseHelper
{
private array $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function parse(?ResponseInterface $response = null): ResponseInterface
{
$response = $response ?: new Response();
if (!$response->getHeader('Content-Type')) {
$response = $response->withHeader('Content-Type', 'application/json');
}
$response->getBody()
->write(json_encode($this->data, JSON_THROW_ON_ERROR));
return $response;
}
}
// src/Infra/Http/Controller
final class UserController
{
private UserListViewModel $user_list_view_model;
public function __construct(UserListViewModel $user_list_view_model)
{
$this->user_list_view_model = $user_list_view_model;
}
public function index(): ResponseInterface
{
return (new JsonResponseHelper($user_list_view_model->fetch()))->parse();
}
}
@patoui
Copy link
Author

patoui commented Oct 13, 2021

Using this gist as a way to share ideas about Clean Architecture structure in PHP

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment