目錄
路由簡介
轉乘路線
範例
輸出
通過的參數
作為操作方法的參數
作為數字索引數組
使用路由數組
產生 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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++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教學
1655
14
CakePHP 教程
1414
52
Laravel 教程
1307
25
PHP教程
1254
29
C# 教程
1228
24
適用於 Ubuntu 和 Debian 的 PHP 8.4 安裝和升級指南 適用於 Ubuntu 和 Debian 的 PHP 8.4 安裝和升級指南 Dec 24, 2024 pm 04:42 PM

PHP 8.4 帶來了多項新功能、安全性改進和效能改進,同時棄用和刪除了大量功能。 本指南介紹如何在 Ubuntu、Debian 或其衍生版本上安裝 PHP 8.4 或升級到 PHP 8.4

在PHP API中說明JSON Web令牌(JWT)及其用例。 在PHP API中說明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

您如何在PHP中解析和處理HTML/XML? 您如何在PHP中解析和處理HTML/XML? Feb 07, 2025 am 11:57 AM

本教程演示瞭如何使用PHP有效地處理XML文檔。 XML(可擴展的標記語言)是一種用於人類可讀性和機器解析的多功能文本標記語言。它通常用於數據存儲

解釋PHP中的晚期靜態綁定(靜態::)。 解釋PHP中的晚期靜態綁定(靜態::)。 Apr 03, 2025 am 12:04 AM

靜態綁定(static::)在PHP中實現晚期靜態綁定(LSB),允許在靜態上下文中引用調用類而非定義類。 1)解析過程在運行時進行,2)在繼承關係中向上查找調用類,3)可能帶來性能開銷。

php程序在字符串中計數元音 php程序在字符串中計數元音 Feb 07, 2025 pm 12:12 PM

字符串是由字符組成的序列,包括字母、數字和符號。本教程將學習如何使用不同的方法在PHP中計算給定字符串中元音的數量。英語中的元音是a、e、i、o、u,它們可以是大寫或小寫。 什麼是元音? 元音是代表特定語音的字母字符。英語中共有五個元音,包括大寫和小寫: a, e, i, o, u 示例 1 輸入:字符串 = "Tutorialspoint" 輸出:6 解釋 字符串 "Tutorialspoint" 中的元音是 u、o、i、a、o、i。總共有 6 個元

什麼是PHP魔術方法(__ -construct,__destruct,__call,__get,__ set等)並提供用例? 什麼是PHP魔術方法(__ -construct,__destruct,__call,__get,__ set等)並提供用例? Apr 03, 2025 am 12:03 AM

PHP的魔法方法有哪些? PHP的魔法方法包括:1.\_\_construct,用於初始化對象;2.\_\_destruct,用於清理資源;3.\_\_call,處理不存在的方法調用;4.\_\_get,實現動態屬性訪問;5.\_\_set,實現動態屬性設置。這些方法在特定情況下自動調用,提升代碼的靈活性和效率。

PHP和Python:比較兩種流行的編程語言 PHP和Python:比較兩種流行的編程語言 Apr 14, 2025 am 12:13 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

See all articles