Skip to content

Instantly share code, notes, and snippets.

@hgraca
Last active August 17, 2017 07:05
Show Gist options
  • Save hgraca/ea2473a0d83a8fd70718b412870881c2 to your computer and use it in GitHub Desktop.
Save hgraca/ea2473a0d83a8fd70718b412870881c2 to your computer and use it in GitHub Desktop.
A simple example of my prefered MVC implementation, with featuring the Model, a View, a Controller, and a ViewModel.
<?php
// src/UI/Admin/Some/Controller/Namespace/Detail/SomeEntityDetailController.php
namespace UI\Admin\Some\Controller\Namespace\Detail;
// use ...
final class SomeEntityDetailController
{
/**
* @var SomeRepositoryInterface
*/
private $someRepository;
/**
* @var RelatedRepositoryInterface
*/
private $relatedRepository;
/**
* @var TemplateEngineInterface
*/
private $templateEngine;
public function __construct(
SomeRepositoryInterface $someRepository,
RelatedRepositoryInterface $relatedRepository,
TemplateEngineInterface $templateEngine
) {
$this->someRepository = $someRepository;
$this->relatedRepository = $relatedRepository;
$this->templateEngine = $templateEngine;
}
/**
* @return mixed
*/
public function get(int $someEntityId)
{
$mainEntity = $this->someRepository->getById($someEntityId);
$relatedEntityList = $this->relatedRepository->getByParentId($someEntityId);
return $this->templateEngine->render(
'@Some/Controller/Namespace/Detail/details.html.twig',
new DetailsViewModel($mainEntity, $relatedEntityList)
);
}
}
<?php
// src/UI/Admin/Some/Controller/Namespace/Detail/DetailsViewModel.php
namespace UI\Admin\Some\Controller\Namespace\Detail;
// use ...
final class DetailsViewModel implements TemplateViewModelInterface
{
/**
* @var array
*/
private $mainEntity = [];
/**
* @var array
*/
private $relatedEntityList = [];
/**
* @var bool
*/
private $shouldDisplayFancyDialog = false;
/**
* @var bool
*/
private $canEditData = false;
/**
* @param SomeEntity $mainEntity
* @param RelatedEntity[] $relatedEntityList
*/
public function __construct(SomeEntity $mainEntity, array $relatedEntityList)
{
$this->mainEntity = [
'name' => $mainEntity->getName(),
'description' => $mainEntity->getResume(),
];
foreach ($relatedEntityList as $relatedEntity) {
$this->relatedEntityList[] = [
'title' => $relatedEntity->getTitle(),
'subtitle' => $relatedEntity->getSubtitle(),
];
}
$this->shouldDisplayFancyDialog = /* ... some complex conditional using the entities data ... */ ;
$this->canEditData = /* ... another complex conditional using the entities data ... */ ;
}
public function getMainEntity(): array
{
return $this->mainEntity;
}
public function getRelatedEntityList(): array
{
return $this->relatedEntityList;
}
public function shouldDisplayFancyDialog(): bool
{
return $this->shouldDisplayFancyDialog;
}
public function canEditData(): bool
{
return $this->canEditData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment