目录
路由简介
转乘路线
示例
输出
通过的参数
作为操作方法的参数
作为数字索引数组
使用路由数组
生成 URL
Output
Redirect Routing
Example
Output for URL 2
首页 后端开发 php教程 CakePHP 路由

CakePHP 路由

Sep 10, 2024 pm 05:25 PM
php cakephp PHP framework

在本章中,我们将学习以下与路由相关的主题 -

  • 路由简介
  • 转乘路线
  • 将参数传递给路由
  • 生成网址
  • 重定向网址

路由简介

在本节中,我们将了解如何实现路由、如何将参数从 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>This is CakePHP tutorial and this is an example of connecting routes.</h1>
登录后复制

通过访问以下 URL 来执行上述示例,该 URL 位于 http://localhost/cakephp4/

输出

上面的 URL 将产生以下输出。

Above 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>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 将产生以下输出。

Passed Argument

生成 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>
登录后复制

Execute the above example by visiting the following URL −

http://localhost/cakephp4/generate

Output

The above URL will produce the following output −

Generating URL

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

Execute URL

URL 2 − http://localhost/cakephp4/redirect

Output for URL 2

You will be redirected to https://tutorialspoint.com

以上是CakePHP 路由的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

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

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1672
14
CakePHP 教程
1428
52
Laravel 教程
1332
25
PHP教程
1276
29
C# 教程
1256
24
PHP与Python:了解差异 PHP与Python:了解差异 Apr 11, 2025 am 12:15 AM

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

PHP:网络开发的关键语言 PHP:网络开发的关键语言 Apr 13, 2025 am 12:08 AM

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

PHP和Python:比较两种流行的编程语言 PHP和Python:比较两种流行的编程语言 Apr 14, 2025 am 12:13 AM

PHP和Python各有优势,选择依据项目需求。1.PHP适合web开发,尤其快速开发和维护网站。2.Python适用于数据科学、机器学习和人工智能,语法简洁,适合初学者。

PHP行动:现实世界中的示例和应用程序 PHP行动:现实世界中的示例和应用程序 Apr 14, 2025 am 12:19 AM

PHP在电子商务、内容管理系统和API开发中广泛应用。1)电子商务:用于购物车功能和支付处理。2)内容管理系统:用于动态内容生成和用户管理。3)API开发:用于RESTfulAPI开发和API安全性。通过性能优化和最佳实践,PHP应用的效率和可维护性得以提升。

PHP的持久相关性:它还活着吗? PHP的持久相关性:它还活着吗? Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在现代编程领域中依然占据重要地位。1)PHP的简单易学和强大社区支持使其在Web开发中广泛应用;2)其灵活性和稳定性使其在处理Web表单、数据库操作和文件处理等方面表现出色;3)PHP不断进化和优化,适用于初学者和经验丰富的开发者。

PHP和Python:解释了不同的范例 PHP和Python:解释了不同的范例 Apr 18, 2025 am 12:26 AM

PHP主要是过程式编程,但也支持面向对象编程(OOP);Python支持多种范式,包括OOP、函数式和过程式编程。PHP适合web开发,Python适用于多种应用,如数据分析和机器学习。

PHP与其他语言:比较 PHP与其他语言:比较 Apr 13, 2025 am 12:19 AM

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP和Python:代码示例和比较 PHP和Python:代码示例和比较 Apr 15, 2025 am 12:07 AM

PHP和Python各有优劣,选择取决于项目需求和个人偏好。1.PHP适合快速开发和维护大型Web应用。2.Python在数据科学和机器学习领域占据主导地位。

See all articles