Skip to content

Instantly share code, notes, and snippets.

@guilhermeblanco
Created May 8, 2014 20:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guilhermeblanco/2a33255e006c11202e86 to your computer and use it in GitHub Desktop.
Save guilhermeblanco/2a33255e006c11202e86 to your computer and use it in GitHub Desktop.
<?php
class TabRepository
{
private $mapping;
public function __construct(/*...*/, TabMapping $mapping)
{
$this->mapping = $mapping;
}
public function findBySlugs($slug, TabType $tabType = null)
{
$sql = sprintf('%s WHERE slug = :slug', $this->getSQL($tabType));
// ...
}
private function getSQL(TabType $tabType = null)
{
if ( ! $tabType) {
$sqlParts = [];
foreach ($this->mapping->getSubclasses() as $discriminatorColumn => $childMapping) {
$sqlParts[] = sprintf(
'SELECT %s, "%s" as type FROM %s',
$childMapping->getColumnList(),
$discriminatorColumn,
$childMapping->getTableName()
);
}
return sprintf('SELECT * FROM (%s)', implode(' UNION ALL ', $sqlParts));
}
$childMapping = $this->mapping->getSubclass($tabType->getSlug());
return sprintf(
'SELECT %s, "%s" as type FROM %s',
$childMapping->getColumnList(),
$tabType->getSlug(),
$childMapping->getTableName()
);
}
}
<?php
class TabTypeMapping extends Mapping
{
public function initialize()
{
$this->addColumn('id', 'integer');
$this->addColumn('name', 'string');
$this->addColumn('slug', 'string');
}
}
<?php
class TabTypeRepository
{
private $data = array();
public function __construct(TabTypeFactory $tabTypeFactory)
{
$this->tabTypeFactory = $tabTypeFactory;
$this->data = [
$this->tabTypeFactory->createFromArray([
'id' => 1,
'name' => 'Violão',
'slug' => 'violao',
]),
// ...
];
}
public function findBySlug($slug)
{
foreach ($this->data as $tabType) {
if ($tabType->getSlug() !== $slug) {
continue;
}
return $tabType;
}
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment