简体   繁体   English

Symfony 2 - 从另一个控制器调用控制器

[英]Symfony 2 - Call controller from another controller

I would like use a method of controller from another bundle, in my controller. 我想在我的控制器中使用来自另一个bundle的控制器方法。

The method this->forward need a Response object, and i don't know how to use it. 方法this-> forward需要一个Response对象,我不知道如何使用它。

public function indexAction($name)
{
$response = $this->forward('AcmeHelloBundle:Hello:fancy', array(
    'name'  => $name,
    'color' => 'green',
));

// ... further modify the response or return it directly

return $response;
}

And i saw that i can use service but i want to know if its the best solution or they are another. 我看到我可以使用服务,但我想知道它是最好的解决方案还是另一种解决方案。

$this->forward takes arguments in this order: $this->forward按此顺序接受参数:

  1. Logical Name of controller action in string format ie 'AcmeHelloBundle:Hello:fancy' 字符串格式的控制器操作的逻辑名称,即'AcmeHelloBundle:Hello:fancy'
  2. Parameters to be passed as request variables in array format ie array( 'name' => $name, 'color' => 'green', ) 以数组格式作为请求变量传递的参数,即array('name'=> $ name,'color'=>'green',)

These parameters can be accessed in the controller using request access functions. 可以使用请求访问功能在控制器中访问这些参数。

Sometimes you want to bypass security completely and run a command in another controller despite a user's permissions level. 有时您希望完全绕过安全性并在另一个控制器中运行命令,尽管用户的权限级别。 Luckily you can do that fairly easily. 幸运的是,你可以相当容易地做到这一点。

First, run a use Command for your controller at the top of the controller you want to use the data from: 首先,在您想要使用以下数据的控制器顶部为您的控制器运行一个use命令:

use AppBundle\Controller\MySourceDataController;

Then call that function from within your destination controller: 然后从目标控制器中调用该函数:

$response = MySourceDataController::getTheData( $option1, $option2 );

If you need to pass a Request object, you can do it this way: 如果需要传递Request对象,可以这样做:

$response = MySourceDataController::getTheData( new Request( array(
    'server' => 'USAServer1',
) ), $option2 );

This returns a Request with the set parameter of server. 这将返回带有server参数的Request。 I also defined a $option2, this would be a variable often defined in the URL such as: 我还定义了一个$ option2,这将是一个经常在URL中定义的变量,例如:

* @Route("/mydata/{server}/", name="api-source-data")
* @param Request $request
* @param         $server

Lastly, if you're passing JSON in that controller and want to convert it back to an object, you can run this bit of code on the $response: 最后,如果您在该控制器中传递JSON并希望将其转换回对象,则可以在$ response上运行以下代码:

if ( 0 === strpos( $response->headers->get( 'Content-Type' ), 'application/json' ) ) {
    $response = json_decode( $response->getContent(), true );
}

Voila. 瞧。 Access any controller form any other controller and bypass security notation for the source controller. 从任何其他控制器访问任何控制器并绕过源控制器的安全符号。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM