简体   繁体   English

Symfony2 redirectToRoute没有返回

[英]Symfony2 redirectToRoute without return

redirectToRoute has to be returned by a controller action to work. redirectToRoute必须由控制器操作返回才能工作。 For example: 例如:

function testAction() {
    return $this->redirectToRoute('homepage');
}

But how is it possible to call the redirect outside the action function (from an another function)? 但是,如何在动作函数外部(从另一个函数)调用重定向? Like: 喜欢:

function checkError() {
    $this->redirectToRoute('error');
}

Controller must return Response. 控制器必须返回响应。 There is no way (almost) to avoid it. 没有办法(几乎)避免它。

What you can do is use exception in your internal function(s), catch exception in controller and return response from controller. 您可以做的是在内部函数中使用异常,在控制器中捕获异常并从控制器返回响应。 Ex. 防爆。

function testAction() {
    try {
        checkError();
    } catch(Exception $e) {
        return $this->redirectToRoute('error');
    }
    $this->redirectToRoute('success');
}

Then in your checkError() function throw an exception. 然后在您的checkError()函数中引发异常。

function checkError() {
    throw new Exception();
}

This is a basic case. 这是一个基本情况。 There are more advanced ways to handle exceptions in Symfony2 and there are more advanced ways of throwing exceptions as well. Symfony2中更高级的 处理异常的方法 ,也有更高级的引发异常的方法

redirectToRoute() will always need to be returned because what it actually does is send a Response to the browser that triggers the redirect. redirectToRoute()将始终需要返回,因为它实际所做的是向浏览器发送响应以触发重定向。 If nothing is returned from a method that has a redirectToRoute() call in it, the redirect doesn't make its way back to the browser and no redirect will happen. 如果调用了redirectToRoute()的方法未返回任何内容,则重定向不会返回到浏览器,也不会发生重定向。

Why not do it like this: 为什么不这样做:

public function testAction() {
    if (checkError()) {
        return $this->redirectToRoute('homepage');
    } else {
        // return normal response
    }
}

private function checkError() {
    //test something
    if ($error) return true; //I know I could just return $error
    return false;            //just making this clear
}

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

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