CakePHP 라우팅

王林
풀어 주다: 2024-09-10 17:25:07
원래의
329명이 탐색했습니다.

이번 장에서는 라우팅과 관련된 다음 주제를 학습하겠습니다. −

  • 라우팅 소개
  • 연결경로
  • 경로에 인수 전달
  • URL 생성
  • 리디렉션 URL

라우팅 소개

이 섹션에서는 경로를 구현하는 방법, 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의 인덱스 메소드를 실행합니다. 두 가지 방법 중 범위 경로 작성이 더 나은 성능을 제공합니다.

연결경로

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>
로그인 후 복사

http://localhost/cakephp4/에 있는 다음 URL을 방문하여 위의 예를 실행하세요

출력

위 URL은 다음과 같은 출력을 생성합니다.

Above URL

통과된 인수

전달된 인수는 URL에 전달된 인수입니다. 이러한 인수는 컨트롤러의 작업에 전달될 수 있습니다. 이렇게 전달된 인수는 세 가지 방법으로 컨트롤러에 제공됩니다.

액션 메소드에 대한 인수

다음 예에서는 컨트롤러 작업에 인수를 전달하는 방법을 보여줍니다. http://localhost/cakephp4/tests/value1/value2

에서 다음 URL을 방문하세요.

다음 경로 노선과 일치합니다.

$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/TemplateTests 폴더를 만들고 해당 폴더 아래에 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 )
로그인 후 복사

위 함수는 두 개의 인수를 사용합니다.

  • 첫 번째 인수는 '컨트롤러', '액션', '플러그인' 중 하나를 지정하는 배열입니다. 또한 라우팅된 요소나 쿼리 문자열 매개변수를 제공할 수 있습니다. 문자열인 경우 유효한 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!