1

I'm building a RESTful API using Symfony2, FOSRestBundle and an OAuth 2 server library.

For any given request, there are a number of possible responses and status codes that I can return to the client.

Take for example the process of getting a user:

<?php

class UserController extends CustomBaseController {


    /**
     * Get a user
     * @Get("/users", name="users_get")
     */
    public function getAction(Request $request) {

        // Ensure a valid access token is present
        $this->validAccessTokenOrExit();

        $user = $this->getUser();
        return $this->handleView($this->view($user, 200));

    }

}

Ideally I would like to have the validAccessTokenOrExit() function terminate the request and return the 401 status code with an appropriate message. This means I can handle authentication in this function and reuse it in several actions across the API.

However I can't seem to find a way of terminating the response from another function, and I always have to return a Response from the action called.

Are there any clean solutions to accomplish this or something similar?

3 Answers 3

1

If you throw an exception that has the interface Symfony\Component\HttpKernel\Exception\HttpExceptionInterface (Symfony\Component\HttpKernel\Exception\HttpException for example) with the status code set (first parameter as 401 for HttpException) it will be handled by the HttpKernel in the way that you are expecting.

For example..

throw new HttpException(401, 'Something went wrong');

.. will be turned into a response with 401 as the status code.

3
  • Thanks for taking a look. The problem with throwing an exception is that on it's own, I couldn't return a response such as: { "code": 401, "error: "Invalid access token" } Throwing an exception is probably the way I'll have to go, but was really looking for a way to have fine control over returning a response from any controller function with any format I specify. Any additional ideas that might help with this? May 29, 2015 at 21:46
  • What do you mean by "with any format I specify"? If you are just wanting to be able to include a message then you just need to do a little bit of messing with the fosrestbundle's config (if that's the issue let me know and I will update my answer), if something else (you mention format too, so I'm not sure) I would need more information but I'm pretty sure it can be done.
    – qooplmao
    May 29, 2015 at 22:12
  • Structure is perhaps a better word to use than format. By structure I mean the 'data structure'. Really I'm just looking for a way to encode an array with the fields I need and return the response somewhere other than the called action. Your suggestion of throwing an Exception does terminate the response but I can only submit a simple message whereas I'll need to add more fields to the returned data. FOSRestBundle does come with a solution for formatting exception response but figuring out how to use it was an uphill battle, so I was hoping to find a native Symfony2 way of accomplishing this. May 30, 2015 at 14:19
0

You can use $this->createAccessDeniedException('message') within a controller.

This will create AccessDeniedException, terminate the current request and return a 403 with your message.

0

I did faced this situation and for time being I call the terminating function with return. Return false from function when valid.

 if($r=$this->validAccessTokenOrExit()){ 
   return $r;
 } 

Alternatively I use following two methods for redirecting or rendering a view form another function and terminating flow.

Redirection:

header('location:'. $this->generateUrl('deals_product_view', array('id' => 1)));
exit;

Rendering a view:

     $response = new Response();    
     $response->setContent($this->renderView($view_file, $params ));
     $response->send();
     exit; 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.