Php 在Symfony 3中捕获所有路线
我在Symfony2有一个全面的后备路线,我无法在Symfony3工作。我尝试了这种精确的语法(我的Symfony2路线的逐字复制),但没有成功Php 在Symfony 3中捕获所有路线,php,routes,yaml,symfony,Php,Routes,Yaml,Symfony,我在Symfony2有一个全面的后备路线,我无法在Symfony3工作。我尝试了这种精确的语法(我的Symfony2路线的逐字复制),但没有成功 fallback: path: /{req} defaults: { _controller: MyBundle:Default:catchAll } requirements: req: ".+" 我怎样才能让它在Symfony3中工作?(这是唯一阻碍我使用Symfony3并让我保持v2.8的因素)这
fallback:
path: /{req}
defaults: { _controller: MyBundle:Default:catchAll }
requirements:
req: ".+"
我怎样才能让它在Symfony3中工作?(这是唯一阻碍我使用Symfony3并让我保持v2.8的因素)这应该可以帮助您:
route1:
path: /{req}
defaults: { _controller: 'AppBundle:Default:index' }
requirements:
req: ".+"
其中,我的控制器名为“DefaultController”,我有一个名为“indexAction()”的函数
以下是我的DefaultController代码:
class DefaultController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
...
我确实在我的环境中尝试了你所说的,直到我指定了正确的控制器设置,它才起作用
编辑: 要使其工作,必须将参数
Request$Request
(带有类型提示)添加到操作的方法签名中。您也可以。
名称空间AppBundle\Controller;
使用Symfony\Component\Debug\Exception\Exception;
使用Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
使用Symfony\Component\HttpFoundation\Request;
使用Symfony\Component\HttpFoundation\Response;
类异常控制器
{
受保护的树枝;
受保护的$debug;
公共函数构造(\Twig\u环境$Twig,$debug)
{
$this->twig=$twig;
$this->debug=$debug;
}
公共函数showAction(请求$Request,异常$exception,DebugLoggerInterface$logger=null)
{
//一些行动
返回新响应($this->twig->render('error/template.html.twig')[
“状态代码”=>$exception->getStatusCode()
]
));
}
}
我发现当前公认的答案对于Symfony 4几乎很有用,因此我将添加我的解决方案:
这就是我在Symfony 4中使其工作所做的:
- 打开
,确保有一个名为/src/Controller/DefaultController.php
index(){}
- 不需要像一些评论所建议的那样,将
添加为第一个参数Request$Request
- 此方法将处理
路由捕获的所有URL。yaml
- 不需要像一些评论所建议的那样,将
- 打开
,添加以下内容:/config/routes.yaml
yourRouteNameHere: path: /{req} defaults: { _controller: 'App\Controller\DefaultController::index' } requirements: # the controller --^ the method --^ req: ".*"` # not ".+"
Request$Request
参数?关于这一点几乎没有文档,因此我首先提出了一个问题。谢谢,这似乎奏效了!你好,这里是@bought777。你不需要那个。我只是剪切粘贴了很多代码。您可以使用以下命令:public function indexAction()
我在没有$request作为参数的情况下尝试了它,但没有成功:OI必须查看控制器代码的其余部分,以便复制正在发生的事情。不管怎样,我想你已经准备好了。享受吧!为什么需要索引?只需使您的控制器可调用。因为这样对初学者来说更容易,而且如果您需要,例如an/admin,也更容易扩展。@emix Magic方法?不用了,谢谢。我非常谨慎地使用它们,这就是我给大多数初学者的建议:谨慎使用它们。我不是说\u set
或\u get
。\uu invoke
方法非常方便,特别是对于控制器和CQ处理程序。这样的对象可以是callable
type提示的类型。
yourRouteNameHere:
path: /{req}
defaults: { _controller: 'App\Controller\DefaultController::index' }
requirements: # the controller --^ the method --^
req: ".*"` # not ".+"