代码区项目交易流程

New in Symfony 4.3: Always Include Route Default Values


Contributed by

Vladimir Luchaninov in #29599 .

In Symfony applications, you can give route placeholders a default value so they can be omitted from the generated URL. Consider this route definition where the page route placeholder provides a default value via the method argument:

namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Routing\Annotation\Route; class BlogController extends AbstractController { /** * @Route("/blog/{page}", name="blog_list") */ public function list($page = 1) { // ... } }

If you don't provide the value of the page variable when generating the URL for the blog_list route, the resulting URL will be /blog and the value of the page placeholder will be 1 :

$router = ... // a UrlGeneratorInterface instance $url = $router->generate('blog_list'); // $url = '/blog' $url = $router->generate('blog_list', ['page' => 1]); // $url = '/blog/1' $url = $router->generate('blog_list', ['page' => 7]); // $url = '/blog/7'

Although this is the desired behavior in most applications, sometimes you may prefer to always include the value of the placeholder, even when you don't provide it while generating the URL. In Symfony 4.3 we made this possible with a new syntax for route placeholders:

/** * @Route("/blog/{!page}", name="blog_list") */ public function list($page = 1) { // ... }

The ! character before the placeholder name tells Symfony to always include its value in the generated URL, no matter if it's a default value:

$url = $router->generate('blog_list'); // $url = '/blog/1' $url = $router->generate('blog_list', ['page' => 1]); // $url = '/blog/1' $url = $router->generate('blog_list', ['page' => 7]); // $url = '/blog/7'

本文开发(php)相关术语:php代码审计工具 php开发工程师 移动开发者大会 移动互联网开发 web开发工程师 软件开发流程 软件开发工程师

点击收藏

LAST Why Use CMB2 Over ACF for Custom Fields in WordPress Serverless PHP on AWS Lamda NEXT