【问题标题】:Yii2, redirect doesn't work in a static functionYii2,重定向在静态函数中不起作用
【发布时间】:2019-08-05 06:53:33
【问题描述】:

这是一种非常奇怪的行为,我从来没有发生过。

我的 SiteController 中有索引操作:

public function actionIndex(){
  Installer::ManageInstall(); //Here I have separated code
  $this->render('myView');. 
}

然后在类Installer的静态函数中:

class Installer {
  public static function ManageInstall(){          
          return  Yii::$app->controller->redirect(['install']);

  }
}

问题是yii完全忽略了重定向,我不知道为什么,从不重定向。

我直接试了,效果不错:

public function actionIndex(){
   return  Yii::$app->controller->redirect(['install']);//Here works fine
        $this->render('myView');. 
     }

你可能会问,因为我做了这个愚蠢的例子,但实际上我已经将代码简化到最低限度,只是为了说明问题。实际上,Installer 类使用另一个条件进行重定向,我没有提出,因为它与问题无关。

我试过用这个表达方式:

     Yii::$app->response->redirect(['install'])->send(); return;

 Yii::$app->controller->redirect('install'); //without Return statement

..什么都没有

【问题讨论】:

    标签: function redirect static yii2


    【解决方案1】:

    它应该这样工作:

    return Yii::$app->response->redirect(['install'])->send();
    

    请告诉我这个结果。

    【讨论】:

    • @TomasGrecioRamirez 你在做 ajax 请求吗?
    • 不,是常规的 Get 请求。我实际上已经跟踪了 Yii Core 代码,并执行了它但它没有重定向,在 yii\web\Response 类的 redirect() 函数的第 884 行,放置一个 die() 函数;并中止。
    • @TomasGrecioRamirez 尝试将 return 添加到 Installer::ManageInstall(); 并让我知道这是怎么回事。它应该看起来像 return Installer::ManageInstall();
    • 是的,它可以工作,但在这种情况下,永远不要通过此代码行,因为 return 在那里。 ManageInstall 函数的目的是评估一些条件;据此,通过或重定向
    • @TomasGrecioRamirez 在做其他事情时,您如何期望它重定向?如果你需要它做其他事情,重定向应该是最后一行代码,即被执行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多