在本章中,我们将学习以下与路由相关的主题 -
- 路由简介
- 转乘路线
- 将参数传递给路由
- 生成网址
- 重定向网址
路由简介
在本节中,我们将了解如何实现路由、如何将参数从 URL 传递到控制器的操作、如何生成 URL 以及如何重定向到特定 URL。通常,路由在文件 config/routes.php 中实现。路由可以通过两种方式实现 -
- 静态方法
- 范围内的路线构建器
这里是一个展示这两种类型的示例。
// Using the scoped route builder. Router::scope('/', function ($routes) { $routes->connect('/', ['controller' => 'Articles', 'action' => 'index']); }); // Using the static method. Router::connect('/', ['controller' => 'Articles', 'action' => 'index']);
这两个方法都会执行ArticlesController的index方法。在这两种方法中,作用域路由构建器提供了更好的性能。
转乘路线
Router::connect()方法用于连接路由。以下是该方法的语法 -
static Cake\Routing\Router::connect($route, $defaults =[], $options =[])
Router::connect() 方法有三个参数 -
第一个参数是您要匹配的 URL 模板。
第二个参数包含路由元素的默认值。
第三个参数包含路由的选项,一般包含正则表达式规则。
这是路线的基本格式 -
$routes->connect( 'URL template', ['default' => 'defaultValue'], ['option' => 'matchingRegex'] );
示例
在 config/routes.php 文件中进行更改,如下所示。
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { // Register scoped middleware for in scopes. $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('/', ['controller' => 'Tests', 'action' => 'show']); $builder->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']); $builder->fallbacks(); });
在 src/Controller/TestsController.php 创建 TestsController.php 文件。 将以下代码复制到控制器文件中。
src/Controller/TestsController.php
<?php declare(strict_types=1); namespace App\Controller; use Cake\Core\Configure; use Cake\Http\Exception\ForbiddenException; use Cake\Http\Exception\NotFoundException; use Cake\Http\Response; use Cake\View\Exception\MissingTemplateException; class TestsController extends AppController { public function show() { } }
在src/Template下创建一个文件夹Tests,并在该文件夹下创建一个名为show.php的视图文件。将以下代码复制到该文件中。
src/Template/Tests/show.php
<h1 id="This-is-CakePHP-tutorial-and-this-is-an-example-of-connecting-routes">This is CakePHP tutorial and this is an example of connecting routes.</h1>
通过访问以下 URL 来执行上述示例,该 URL 位于 http://localhost/cakephp4/
输出
上面的 URL 将产生以下输出。

通过的参数
传递的参数是在 URL 中传递的参数。这些参数可以传递给控制器的操作。这些传递的参数通过三种方式提供给您的控制器。
作为操作方法的参数
以下示例显示了我们如何将参数传递给控制器的操作。访问以下 URL:http://localhost/cakephp4/tests/value1/value2
这将匹配以下路线。
$builder->connect('tests/:arg1/:arg2', ['controller' => 'Tests', 'action' => 'show'],['pass' => ['arg1', 'arg2']]);
这里,URL 中的 value1 将被分配给 arg1,value2 将被分配给 arg2。
作为数字索引数组
将参数传递给控制器的操作后,您可以使用以下语句获取参数。
$args = $this->request->params[‘pass’]
传递给控制器操作的参数将存储在 $args 变量中。
使用路由数组
参数也可以通过以下语句传递给操作 -
$routes->connect('/', ['controller' => 'Tests', 'action' => 'show',5,6]);
上面的语句将向 TestController 的 show() 方法传递两个参数 5 和 6。
示例
在 config/routes.php 文件中进行更改,如以下程序所示。
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { // Register scoped middleware for in scopes. $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('tests/:arg1/:arg2', ['controller' => 'Tests', 'action' => 'show'],['pass' => ['arg1', 'arg2']]); $builder->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']); $builder->fallbacks(); });
在 src/Controller/TestsController.php 创建 TestsController.php 文件。 将以下代码复制到控制器文件中。
src/Controller/TestsController.php
<?php declare(strict_types=1); namespace App\Controller; use Cake\Core\Configure; use Cake\Http\Exception\ForbiddenException; use Cake\Http\Exception\NotFoundException; use Cake\Http\Response; use Cake\View\Exception\MissingTemplateException; class TestsController extends AppController { public function show($arg1, $arg2) { $this->set('argument1',$arg1); $this->set('argument2',$arg2); } }
在 src/Template 创建一个文件夹 Tests 并在该文件夹下创建一个名为 show.php 的 View 文件。将以下代码复制到该文件中。
src/Template/Tests/show.php.
<h1 id="This-is-CakePHP-tutorial-and-this-is-an-example-of-Passed-arguments">This is CakePHP tutorial and this is an example of Passed arguments.</h1> <?php echo "Argument-1:".$argument1."<br/>"; echo "Argument-2:".$argument2."<br>"; ?>
通过访问以下 URL http://localhost/cakephp4/tests/Virat/Kunal
执行上面的示例输出
执行后,上述 URL 将产生以下输出。

生成 URL
这是 CakePHP 的一个很酷的功能。使用生成的 URL,我们可以轻松更改应用程序中 URL 的结构,而无需修改整个代码。
url( string|array|null $url null , boolean $full false )
上面的函数将接受两个参数 -
第一个参数是一个数组,指定以下任意一项 - 'controller'、'action'、'plugin'。此外,您还可以提供路由元素或查询字符串参数。如果是字符串,则可以给定任何有效 url 字符串的名称。
如果为 true,完整的基本 URL 将被添加到结果中。默认为 false。
示例
在 config/routes.php 文件中进行更改,如以下程序所示。
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { // Register scoped middleware for in scopes. $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('/generate',['controller'=>'Generates','action'=>'show']); $builder->fallbacks(); });
Create a GeneratesController.php file at src/Controller/GeneratesController.php. Copy the following code in the controller file.
src/Controller/GeneratesController.php
<?php declare(strict_types=1); namespace App\Controller; 21 use Cake\Core\Configure; use Cake\Http\Exception\ForbiddenException; use Cake\Http\Exception\NotFoundException; use Cake\Http\Response; use Cake\View\Exception\MissingTemplateException; class GeneratesController extends AppController { public function show() { } }
Create a folder Generates at src/Template and under that folder, create a View file called show.php. Copy the following code in that file.
src/Template/Generates/show.php
<h1>This is CakePHP tutorial and this is an example of Generating URLs<h1> </h1> </h1>
Execute the above example by visiting the following URL −
http://localhost/cakephp4/generate
Output
The above URL will produce the following output −

Redirect Routing
Redirect routing is useful, when we want to inform client applications that, this URL has been moved. The URL can be redirected using the following function −
static Cake\Routing\Router::redirect($route, $url, $options =[])
There are three arguments to the above function as follows −
A string describing the template of the route.
A URL to redirect to.
An array matching the named elements in the route to regular expressions which that element should match.
Example
Make Changes in the config/routes.php file as shown below. Here, we have used controllers that were created previously.
config/routes.php
<?php use Cake\Http\Middleware\CsrfProtectionMiddleware; use Cake\Routing\Route\DashedRoute; use Cake\Routing\RouteBuilder; $routes->setRouteClass(DashedRoute::class); $routes->scope('/', function (RouteBuilder $builder) { // Register scoped middleware for in scopes. $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 'httpOnly' => true, ])); $builder->applyMiddleware('csrf'); $builder->connect('/generate',['controller'=>'Generates','action'=>'show']); $builder->redirect('/redirect','https://tutorialspoint.com/'); $builder->fallbacks(); });
Execute the above example by visiting the following URLs.
URL 1 − http://localhost/cakephp4/generate
Output for URL 1

URL 2 − http://localhost/cakephp4/redirect
Output for URL 2
You will be redirected to https://tutorialspoint.com
以上是CakePHP 路由的详细内容。更多信息请关注PHP中文网其他相关文章!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境