Skip to content

Instantly share code, notes, and snippets.

@uwej711
Created March 28, 2012 14:05
Show Gist options
  • Select an option

  • Save uwej711/2226457 to your computer and use it in GitHub Desktop.

Select an option

Save uwej711/2226457 to your computer and use it in GitHub Desktop.
EntityRouter
<?php
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Generator\UrlGenerator;
class EntityRouter implements RouterInterface
{
const NAME = 'entity';
protected $context;
protected $service;
protected $route;
protected $collection;
protected $generator;
public function __construct(ServiceInterface $service, RequestContext $context)
{
$this->service = $service;
$this->context = $context;
$this->route = new Route('/{slug}', array('_controller' => '<put a default here>'),array('slug' => '.+'));
$this->collection = new RouteCollection();
$this->collection->add(self::NAME, $this->route);
$this->generator = new UrlGenerator($this->collection, $this->context);
}
public function setContext(RequestContext $context)
{
$this->context = $context;
$this->generator->setContext($context);
}
public function getContext()
{
return $this->context;
}
public function getRouteCollection()
{
return $this->collection;
}
public function generate($name, $parameters = array(), $absolute = false)
{
return $this->generator->generate($name, $parameters, $absolute);
}
public function match($pathinfo)
{
$slug = substr($pathinfo, 1);
$entity = $this->service->getEntityBySlug($slug);
if (null === $entity) {
throw new ResourceNotFoundException("No entity for slug $slug found");
}
return array_merge($this->route->getDefaults(), array('_route' => self::NAME, 'entity' => $entity));
}
}
@lwojciechowski

Copy link
Copy Markdown

Really nice work. I think I could use that! Thanks.

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