Created
May 3, 2012 12:14
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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