Skip to content

Instantly share code, notes, and snippets.

@alganet
Created March 17, 2011 00:34
Show Gist options
  • Save alganet/873632 to your computer and use it in GitHub Desktop.
Save alganet/873632 to your computer and use it in GitHub Desktop.
Exploring Respect\Rest concepts
<?php
use Respect\Config\Container;
use Respect\Rest\Dispatcher;
use Respect\Rest\Routers\Fixed;
use Respect\Validation\Validator;
use Doctrine\ORM\EntityManager;
use Twig_Environment;
// see http://github.com/Respect/Config
$config = new Container('config.ini');
$config->em = function() use ($config) {
return EntityManager::create($config->connectionOptions, $config->doctrineConfiguration);
};
$config->view = function() use ($config) {
return new Twig_Environment($config->twigLoader, $config->twigConfiguration);
};
$config->valid = function() use ($config) {
return Validator::string()->noWhitespace()->length(1,15);
};
$dispatcher = new Dispatcher();
$dispatcher->setServiceLocator($config);
$dispatcher->setRouter(new Fixed);
$dispatcher->run();
<?php
namespace Users;
use Doctrine\ORM\EntityManager as Entities;
use Doctrine\ORM\EntityNotFoundException;
use Twig_Environment as Templates;
use Respect\Validation\Validatable as Validator;
use Respect\Validation\Exceptions\ValidationException;
// Zero parameters maps to collections http://example.com/users/
class Collection
{
//Auto injected from the context $context->em, $context->view
public function get(Entities $em, Templates $view)
{
$users = $em->getRepository('User')->findAll();
return $view->loadTemplate('user.phtml')->render($users);
}
}
<?php
namespace Users;
use Doctrine\ORM\EntityManager as Entities;
use Doctrine\ORM\EntityNotFoundException;
use Twig_Environment as Templates;
use Respect\Validation\Validatable as Validator;
use Respect\Validation\Exceptions\ValidationException;
// Single parameter maps to resource http://example.com/users/foobar
class Resource
{
protected $userName;
public function __construct($userName) //"foobar" is used here
{
$this->userName = $userName;
}
//Auto injected from the context $context->em, $context->view, $context->valid
public function get(Entities $em, Templates $view, Validator $valid)
{
try {
$valid->assert($this->userName);
$user = $em->getRepository('User')->findOneBy(array('screen_name' => $this->userName));
return $view->loadTemplate('user.phtml')->render($user);
} catch (ValidationException $e) {
return new Respect\Rest\Responses\Error($e->getMessage());
} catch (EntityNotFoundException $e) {
return new Respect\Rest\Responses\NotFoundError($e->getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment