CakePHP ルーティング

王林
リリース: 2024-09-10 17:25:07
オリジナル
483 人が閲覧しました

この章では、ルーティングに関連する次のトピックについて学習します -

  • ルーティングの概要
  • 接続ルート
  • 引数をルートに渡す
  • URL を生成しています
  • リダイレクト URL

ルーティングの概要

このセクションでは、ルートを実装する方法、URL からコントローラーのアクションに引数を渡す方法、URL を生成する方法、特定の URL にリダイレクトする方法について説明します。通常、ルートはファイル config/routes.php に実装されます。ルーティングは 2 つの方法で実装できます -

  • 静的メソッド
  • スコープ付きルートビルダー

ここでは、両方のタイプを示す例を示します。

// 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 のインデックス メソッドを実行します。 2 つの方法のうち、スコープ ルート ビルダー の方がパフォーマンスが優れています。

接続ルート

Router::connect() メソッドはルートの接続に使用されます。以下はメソッドの構文です -

static Cake\Routing\Router::connect($route, $defaults =[], $options =[])
ログイン後にコピー

Router::connect() メソッドには 3 つの引数があります -

  • 最初の引数は、照合する URL テンプレートです。

  • 2 番目の引数には、ルート要素のデフォルト値が含まれます。

  • 3 番目の引数にはルートのオプションが含まれており、通常は正規表現ルールが含まれます。

これはルートの基本的な形式です -

$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>
ログイン後にコピー

http://localhost/cakephp4/ にある次の URL にアクセスして、上記の例を実行します

出力

上記の URL は次の出力を生成します。

Above URL

渡された引数

渡された引数は、URL で渡される引数です。これらの引数はコントローラーのアクションに渡すことができます。これらの渡された引数は、3 つの方法でコントローラーに与えられます。

アクションメソッドの引数として

次の例は、コントローラーのアクションに引数を渡す方法を示しています。次の 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]);
ログイン後にコピー

上記のステートメントは、2 つの引数 5 と 6 を TestController の show() メソッドに渡します。

次のプログラムに示すように、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 )
ログイン後にコピー

上記の関数は 2 つの引数を取ります -

  • 最初の引数は、'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 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!