Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@coreymcmahon
Created May 3, 2012 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coreymcmahon/2585264 to your computer and use it in GitHub Desktop.
Save coreymcmahon/2585264 to your computer and use it in GitHub Desktop.
A very simple Symfony controller demonstrating the use of the Doctrine ORM - http://www.symfonycentral.com
<?php
namespace MyCompany\BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
/* Note below: we NEEED to include the Entity class Doctrine built for us */
use MyCompany\BlogBundle\Entity\Post as Post;
class DefaultController extends Controller
{
/**
* @Route("/article/{id}", name="blog_view", requirements={"id" = "\d+"})
* @Template()
*/
public function indexAction($id)
{
/* We use the Doctrine Repository object to search the database */
$post = $this->getDoctrine()
->getRepository('MyCompanyBlogBundle:Post')
->find($id);
if (!$post) {
return array('body' => '', 'title' => '');
}
/* If a matching post was found for the ID, use the entity object */
return array(
'body' => $post->getBody(),
'title' => $post->getTitle()
);
}
/**
* @Route("/article/add", requirements={"_method" = "GET"})
* @Template()
*/
public function addAction()
{
return array();
}
/**
* @Route("/article/add", requirements={"_method" = "POST"})
* @Template()
*/
public function saveAction()
{
$request = $this->getRequest();
$title = $request->get('title');
$body = $request->get('body');
/* Construct the Entity using the values provided in the form */
$post = new Post();
$post->setTitle($title);
$post->setBody($body);
/* We use the Doctrine "EntityManager" to persist objects */
$em = $this->getDoctrine()->getEntityManager();
$em->persist($post);
$em->flush();
/* The object isn't saved UNTIL we call ->flush... */
return $this->redirect($this->generateUrl('blog_view', array('id' => $post->getId())));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment