2014-08-29 58 views
-1

以下是大图:我正在为我的web应用程序编写symfony2包。此应用程序包含一个带有CRUD控制器的标准网站。另一方面,它包含一个rest API,它还管理创建/编辑/ ......实体。Subrequests with post vars

我开始为User实体编写Rest\UserController。它包含所有标准REST操作(GET,POST,PUT,DELETE)。这是基于威廉杜兰德非常好的教程:http://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/

一旦创建和功能,我已创建另一个UserController来处理应用程序的网络端。在这个控制器中,我有一个名为editAction的动作,它在HTML响应中呈现一个表单。此表格在提交时会向同一控制器的动作putAction发送PUT请求。我的想法是将请求转发到Rest\UserController并采取行动putAction。下面是UserController::putAction代码:

/** 
    * This action forwards the request to the REST controller. It redirects 
    * to a user list upon success, or displays the message should an error 
    * occur. 
    * @Route("/{id}/put", name="igt_user_put") 
    * @Method("PUT") 
    */ 
    public function putAction (User $user) 
    { 
     $response = $this->forward('MyBundle:Rest\User:put', array('id'=>$user->getId())); 
     if ($response->getStatusCode() == Response::HTTP_NO_CONTENT) { 
      return new RedirectResponse($this->generateUrl('igt_user_list')); 
     } 
     return $response; 
    } 

这就像一个魅力和它的感觉就像是做它的好办法。问题出现时,我想我会做同样的用户激活/停用。我在UserController中有一个lockAction,它会通过“Rest \ UserController :: putAction”运行一个请求,并用合成数据来改变启用字段。

但是我的问题是似乎没有办法设置在前向调用中的POST变量(只有路径和查询),我甚至尝试使用$ kernel-> handle($ request),但没有找到我的Rest控制器的路由。 ?

回答

1

我不确定这是否有效,但您可以尝试。

// Framework controller class 
public function forward($controller, array $path = array(), array $query = array()) 
{ 
    $path['_controller'] = $controller; 
    $subRequest = $this->container->get('request_stack') 
     ->getCurrentRequest()->duplicate($query, null, $path); 

    return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST); 
} 

我们可以看到它重复了当前的请求,然后处理它。

// Request 
/** 
* Clones a request and overrides some of its parameters. 
* 
* @param array $query  The GET parameters 
* @param array $request The POST parameters 
* @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) 
* ... 
*/ 
public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null) 
{ 

因此,重复的方法将采用post变量数组。所以尝试这样的:

public function forwardPost($controller, 
    array $path = array(), 
    array $query = array(), 
    array $post = array()) 
{ 
    $path['_controller'] = $controller; 
    $subRequest = $this->container->get('request_stack') 
     ->getCurrentRequest()->duplicate($query, $post, $path); 

    return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST); 
} 

请好奇,看看这是否会工作。我总是将我的REST设置为一个单独的应用程序,然后使用guzzle来连接它。但转发会更快。

+0

谢谢,这工作(应该看看Controller :: forward方法)。但是这引发了一个新问题,参见[extract-data-from-form-objects-as-array-of-values](http://stackoverflow.com/questions/25576059/extract-data-from-form-objects-as -array-的值) – 2014-08-29 20:51:31