Php 试图调用名为“的未定义方法”;重定向";Symfony 4中的错误
我的代码中有此错误,我编写了“使用”,但我有此错误: 试图调用类的名为“redirect”的未定义方法 “应用程序\控制器\设置本地控制器” 我的代码:Php 试图调用名为“的未定义方法”;重定向";Symfony 4中的错误,php,symfony,symfony4,Php,Symfony,Symfony4,我的代码中有此错误,我编写了“使用”,但我有此错误: 试图调用类的名为“redirect”的未定义方法 “应用程序\控制器\设置本地控制器” 我的代码: <?php namespace App\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Sessi
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\RedirectResponse;
class SetlocaleController extends HomeController {
public function __construct(\Twig\Environment $twig)
{
$this->twig = $twig;
}
public function setLocaleAction(Request $request, $language = null)
{
if($language != null)
{
$session->set('_locale', $language);
}
$url = $request->headers->get('referer');
if(empty($url))
{
return new response($this->twig->render('page/home.html.twig'));
}
else{
return $this->redirect($url);
}
}
}
最佳实践解决方案
正如Symfony在控制器最佳实践文档中所建议的那样,请确保在控制器上扩展抽象控制器
// HomeController.php
// ...
class HomeController extends AbstractController {
// ...
setLocaleControl
无需额外更改。但是,如果不再使用RedirectResponse
,则可以删除它的导入
使用Symfony\Component\HttpFoundation\RedirectResponse代码>
使用HttpFoundation\RedirectResponse的解决方案
您需要使用已导入的重定向响应
对象。不要使用代码:return$this->redirect($url)代码>因为,正如错误所述,没有为类定义重定向(url)
函数
return new RedirectResponse($url);
您使用的方法是$this->redirect()
,但没有这种方法。您的HomeController
是否从AbstractController
扩展而来?请检查您的HomeController是否从AbstractController扩展到使用“$this->redirect()”helperAs ninjaTN说(我想是这样的),最好使用symfony提供的帮助程序。检查您的控制器是否正在扩展AbstractController
,如果不添加它,它将简化您以后的生活:@Etshy我已经用最佳实践解决方案更新了答案。谢谢你们两位的意见