CakePHP Routes

  • Routing allows you to map your URLs to specific controller actions.
  • Routes are defined in the config/routes.php
  • How you may skip arguments from URL to controller’s action, how you may generate URLs, and how can you redirect to a specific URL.
  • By default, CakePHP works on Scoped path builder routes.
  • We can also create custom routes.
CakePHP Routes

Routes are used to define the controller name and their action in Config/routes.php.  There are two ways to represents the routing in CakePHP.

  1. Static method – static method of the routes defines at the outside of the scoped route method.
  2. Scoped path builder – This method defines in between Router::scope with creating a $routes object.

Syntax for static method:

Routes::connect( ‘/‘ , [ ‘controller’ =>‘ControllerName’ , ‘action’ => ‘actionName’ ] ); 

You can also define a name in the router for calling the controller and action directly in the localhost.

Like:

Router::connect('/contact-us', ['controller' => ‘Second’ , 'action' => 'fun']);   

Example of static routing

Here routes.php file in www\CakePHP3.8\config\routes.php.

<?php
 use Cake\Routing\RouteBuilder;
 use Cake\Routing\Router;
 use Cake\Routing\Route\DashedRoute;
 use Cake\Core\Plugin;
 Router::defaultRouteClass(DashedRoute::class);
 Router::connect('/contact-us', ['controller' => ‘Second’ , 'action' => 'fun']); //static routing
 Router::scope('/', function (RouteBuilder $routes) {
 $routes->fallbacks (DashedRoute::class);
 });
 Plugin::routes();
 } 

We have created the SecondController.php file in the controller folder.

     <?php
                 namespace App\Controller;
                 use App\Controller\AppController;
                 class SecondController extends AppController
                    {
                                                 public function fun2()
                                                 {                                                                              
                                                 }
                                 }
 ?> 

Now we have to create fun2.ctp file in src/Template/Second/fun2.ctp and type this message in this file  

hi amit, how are you? have you define the path of routes in config/routes.php ?.

When you run this program on the browser by writing as localhost/CakePHP3.8/contact-us

Then it will show this output.

CakePHP Routes 1

Now we will learn about scoped route builders.

Syntax 

 Router::scope( ‘/’ , function ($routes) {
 $routes -> connect( ‘/’ , [ ‘controller’ => ‘ControllerName’ , ‘action’ => ‘actionName’ ]);
}

Similarly, you can define a router name in scoped path builder:

$routes->connect('/routername', ['controller'
=> 'First', 'action' => 'actionname']);

Example of scoped path builder routing

Here routes.php file in www\CakePHP3.8\config\routes.php

 <?php
 use Cake\Routing\RouteBuilder;
 use Cake\Routing\Router;
 use Cake\Routing\Route\DashedRoute;
 use Cake\Core\Plugin;
 Router::defaultRouteClass(DashedRoute::class);
 Router::scope('/', function (RouteBuilder $routes) {
 $routes->connect( ‘/connect-us’’ , [ ‘controller’ => ‘Second’ , ’action’ => ‘fun2’]);
 $routes->connect( ‘/about-us’ , [ ‘controller’ => ‘Second’ , ’action’ => ‘index’]);
  $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
 $routes->fallbacks (DashedRoute::class);
 });
 Plugin::routes();
 } 

Here is the file of SecondController.php 

 <?php
                namespace App\Controller;
                use App\Controller\AppController;
                class SecondController extends AppController
                   {
                                                public function fun2()
                                                {                                                                             
                                                }
                                }
 ?> 

Now we have to create fun2.ctp file in src/Template/Second/fun2.ctp. Now write some message in this file like-  

hi amit, how are you?.have
you define the path of routes in config/routes.php ?.

When we run this program on localhost/CakePHP3.8/contact-us

Then it will show this output

CakePHP Routes 2

Passing the argument through URLs to controllers

We can pass the arguments in routes either static method or scoped path builder at routes.php file. Here we passed two arguments para1 and para2 after the routes name contact-us with this symbol “:” as a prefix for passing the parameter in routes.php file with array ‘pass’ which define the value of arguments.

.Router::connect('/contact-us/:para1/:para2',
['controller' => 'Second', 'action' =>
'fun2'],["pass"=>["para1","para2”]]);

This is routes.php file in the src/config folder.

 <?php
 use Cake\Routing\RouteBuilder;
 use Cake\Routing\Router;
 use Cake\Routing\Route\DashedRoute;
 use Cake\Core\Plugin;
 Router::defaultRouteClass(DashedRoute::class);
 Router::connect('/contact-us/:para1/:para2', ['controller' => 'Second', 'action' => 'fun2'],["pass"=>["para1","para2”]]);
 Router::scope('/', function (RouteBuilder $routes) {
 //$routes->connect( ‘/about-us’ , [ ‘controller’ => ‘Second’ , ’action’ => ‘index’]);
  //$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
 $routes->fallbacks (DashedRoute::class);
 });
 Plugin::routes();
 } 

We have a SecondController.php file in which we have to create a function fun2().

 <?php
                namespace App\Controller;
                use App\Controller\AppController;
                class SecondController extends AppController
                   {
                                                public function fun2()
                                                {
                                                                print_r($this->request->params['pass']);                                                        
                                                }
                                }
 ?> 

Now we have to create fun2.ctp file in src/Template/Second/fun2.ctp where we have written a short message.  

hi amit, how are you?.have
you define the path of routes in config/routes.php ?.

When you visit the given url and pass, java and / Tpoint values in the localhost like

localhost/CakePHP3.8/contact-us/java/Tpoint

 Output

CakePHP Routes 3

Here we pass two values in URL java and Tpoint with the use of ( /). It shows the output in array form wherein the 0th index of an array in java and 1st index Tpoint. We can also show one value in output by defining the index in controller.php file like

public function fun2()
       {
print_r($this->request->params['pass'][0]);                                                   
       } 

Output

CakePHP Routes 4

There is another method for passing the single argument in the controller.

public function fun2($arg1, $arg2)
    {
echo $arg1;                                         
    } 

Generating Url in browser

If you want to access the path of the file in browser, you can find it easily by passing the given below syntax in initialize method of controller.php file.

 $this->url = Router::url("/",true);
 print_r($this->url); 

Router::url(“/” , true) is a function through which we can access the file path of our web application. The first argument (“/”) is used to show the file path, and the second argument contains the true or false value for showing the full or half route of the source file. Furthermore, it includes a variable url which holds the source path of your data.

You can also set the router name in Route::url("/contact-us"), then it'll show the path from localhost to the contact-us file in a browser.

 <?php
             namespace App\Controller;
             use App\Controller\AppController;
             use Cake\Routing\Router;    
             class SecondController extends AppController 
                         {
                                     public $url;  // here $url is variable
                                     public function initialize(){
                                                 parent::initialize();
                                                 $this->url = Router::url("/",true);
                                     print_r($this->url);
                                     }
                                     public function fun3()
                                     {  
                                  }
                     }
 ?> 

Output

CakePHP Routes 5

And if you want to show the half path on the browser, then you have to pass false in the given below syntax

 Router::url("/",false); and it will show the given below output on the screen.

http://localhost/CakePHP3.8/

If you want to terminate the url, then you can use die; function after the print_r($this->url) in your controller.

Redirect the action within the same controller

We can use the setAction() method to redirect a user to another action of the same controller. The syntax for the setAction() form is as follows:

Cake\Controller\Controller::setAction($action,$args...)

The following code will redirect your action to another action of the same controller.

Syntax

 $this->setAction('index');

The following example shows the usage of the redirect method in your controller. Firstly, you have to perform some changes in the config/routes.php file as shown in the following program.

config/routes.php

 <?php
 use Cake\Routing\RouteBuilder;
 use Cake\Routing\Router;
 use Cake\Routing\Route\DashedRoute;
 Router::defaultRouteClass( DashedRoute :: class );
  Router::scope( '/ ', function ( RouteBuilder $routes ) {         
  $routes->connect( '/ redirect2' ,[ 'controller'=> 'First' ,'action'=>'action2' ] );
              $routes->connect( '/ redirect1', [ 'controller' => 'First', 'action' => 'fun' ] );
               $routes->fallbacks( DashedRoute ::class );
 });
 ?> 

Create the FirstController.php file at src/Controller/FirstController.php. Now write the following code in the controller file.

 <?php
    namespace App\Controller;
    use App\Controller\AppController;
    public function FirstController extends AppController{
       public function fun(){
       }
       public function action2(){
          echo "redirecting from action2";
          $this->setAction('fun');
       }
    }
 ?> 

After that create a folder First at src/Template and that folder you have to create your action file as fun.ctp. Now write the following text in your fun.ctp file.

This is an example of how to redirect within the controller.

Run your program at localhost: - http://localhost/CakePHP3.8/redirect1.

Output

CakePHP Routes 6

Now, visit the following URL ? http://localhost//CakePHP/redirect2.

CakePHP Routes 7



ADVERTISEMENT
ADVERTISEMENT