Skip to content

Instantly share code, notes, and snippets.

@davedevelopment
Created November 26, 2012 23:45
Show Gist options
  • Save davedevelopment/4151421 to your computer and use it in GitHub Desktop.
Save davedevelopment/4151421 to your computer and use it in GitHub Desktop.
Silex Route Helpers
<?php
use Silex\Application;
use Demo\Entity\Post;
use Demo\Controller\PostController;
$app = new Application;
$app['route_class'] = 'CustomRoute';
$app['dispatcher']->addSubscriber(new TemplateRenderingListener($app));
/**
* Todo:
* * Custom Controller Resolver as per http://davedevelopment.co.uk/2012/10/03/Silex-Controllers-As-Services.html
* * Setup Twig
* * Setup Doctrine ORM
*/
$app['findOr404Factory'] = $app->protect(function($type, $message = null) use ($app) {
if (null === $message) {
$lastNamespace = strrpos($type, "\\");
if ($lastNamespace !== false) {
$message = substr($type, strrpos($type, "\\") + 1) . " Not Found";
} else {
$message = "$type Not Found";
}
}
return function($id) use ($app, $type, $message) {
$obj = $app['em']->getRepository($type)->find($id);
if (null === $obj) {
return $app->abort(404, $message);
}
return $obj;
};
});
/**
* Routes
*/
$app->get("/posts/{post}", "posts.controller:viewAction")
->convert("post", $app['findOr404Factory']("Demo\Entity\Post"))
->template("post/edit.html.twig");
<?php
namespace Demo\Controller;
use Demo\Entity\User;
class PostController
{
public function viewAction(Post $post)
{
/** Do something clever */
return array("post" => $post);
}
}
<?php
namespace Demo;
use Silex\Route;
class CustomRoute extends Route
{
public function template($path)
{
$this->setOption('_template', $path);
return $this;
}
}
<?php
namespace Demo\EventListener;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
class TemplateRenderingListener implements EventSubscriberInterface
{
protected $app;
public function __construct(Application $app)
{
$this->app = $app;
}
public function onKernelView(GetResponseForControllerResultEvent $event)
{
$response = $event->getControllerResult();
if (!is_array($response)) {
return;
}
$request = $event->getRequest();
$routeName = $request->attributes->get('_route');
if (!$route = $this->app['routes']->get($routeName)) {
return;
}
if (!$template = $route->getOption('_template')) {
return;
}
$output = $this->app['twig']->render($template, $response);
$event->setResponse(new Response($output));
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::VIEW => array('onKernelView', -10),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment