Symfony2 Controller Coding Style

1) Return a single object

$school = $em->getRepository("AcademicBundle:School")
          ->findOneBy(['id' => $user->getSchoolId()]);
// This may return a single or null
so must check for null
        // Types of Exceptions : Play around with these
        // 404 Exceptions
        throw $this->createNotFoundException('Unable to find entity.');
        throw new NotFoundHttpException('Sorry not existing!');
        //500 Exceptions
        throw $this->createException('Something went wrong');
        throw new Symfony\Component\HttpKernel\Exception\HttpException(500, "Some description");
        // This one is used if the user doesn't have access to that action or page
        throw $this->createAccessDeniedException("You don't have access to this page!");

2) Return a multiple objects

$schools = $em->getRepository("AcademicBundle:School")
                ->findBy(['id' => $user->getSchoolId()]);
// This always returns an array ( empty or full )
if(count($schools)  == 0){
        // $schools is empty 

3) For Transactions

    try {
            //Commit 1
            //Commit 2
            //Commit 3
            // If any of commits 1,2,3 fail then all commits will be reverted
    }catch (Exception $ex) {
        throw $ex;

Leave a Reply

Your email address will not be published. Required fields are marked *