Skip to content

Instantly share code, notes, and snippets.

@geerteltink
Created November 1, 2014 21:36
Show Gist options
  • Save geerteltink/1d5f107a2b099405de9f to your computer and use it in GitHub Desktop.
Save geerteltink/1d5f107a2b099405de9f to your computer and use it in GitHub Desktop.
Symfony 2 Dynamic Router
<?php
namespace Acme\ContentBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
/**
* Dynamic router controller
*
* Tries to locate resources by a given path.
*/
class DynamicRouterController extends Controller
{
/**
* Dynamic content loader
*
* Takes the resource path and search for it in the content table.
*
* @param Request $request
* @param $guid
* @return \Symfony\Component\HttpFoundation\Response
*/
public function getResourceByGuidAction(Request $request, $guid)
{
$contentService = $this->get('acme.content.content.service');
// Redirect /wiki to /wiki/main-page
if ($guid === 'wiki') {
return $this->redirect('/wiki/main-page', 301);
}
$entity = $contentService->findOneByGuid($guid);
if (!$entity) {
throw $this->createNotFoundException(sprintf('No resource found for "%s /%s"',
$request->getMethod(),
$guid
));
}
// TODO: Do some tests to check if the content is already published and not yet expired
return $this->render('AcmeContentBundle:Content:get.html.twig', array(
'entity' => $entity
));
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">
<!-- This is the dynamic content loader, it should always be last! -->
<route id="content.guid" path="/{guid}">
<default key="_controller">AcmeContentBundle:DynamicRouter:getResourceByGuid</default>
<requirement key="_method">get</requirement>
<requirement key="guid">.+</requirement>
</route>
</routes>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment