How To Handle CakePHP 4 Routes in Application Tutorial

Reading Time: 10 minutes
88 Views

Inside this article we will see the concept of How To Handle CakePHP 4 Routes in Application Tutorial. Article contains classified information about Working with CakePHP 4 Routes.

Routes are the basic elements of any web application. Routes can be configured either by any parameter into URL, by using any namespace etc. Application can flow from one end to other end by means of creating application routes.

Routes are a technique in CakePHP 4 that allows you to define URL patterns and link them to specific controllers and actions within a web application.

Learn More –

Let’s get started.


CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.


What are Routes in Web Application ?

In web development, Routes are basically a mechanism where application’s HTTP requests are handled. Request is of any method type like – GET, POST, PUT, DELETE etc

Every web application needs route. It’s declaration is only different according to programming syntax.

For example, have a look few sample CakePHP 4 Routes

//...

$builder->connect('/call-me', array('controller' => 'User', 'action' => 'callMe'));
$builder->connect('/message-me', array('controller' => 'User', 'action' => 'messageMe'));

Important points regarding CakePHP 4 Routes

  • Routes allows us to map application URLs to it’s controllers & it’s actions.
  • Routes are configured and/or defined in [project]/config/routes.php
  • By the help of Routes, we can configure to required or optional parameters in the URL.
  • By default CakePHP uses RouteBuilder $builder class for routes configuration.

About CakePHP 4 Route/Routing

In CakePHP 4.x routes can be configured inside [project]/config/routes.php. It manages and/or handles every HTTP requests.

CakePHP 4.x uses RouteBuilder $builder for routes configuration. While defining routes in application, generally it points to application controller and it’s action.

For example –

$builder->connect('/call-me', array('controller' => 'User', 'action' => 'callMe'));

Route : /call-me Controller : User Method : callMe()

It means, inside CakePHP application we should have a Controller with the name of UserController.php and inside that controller file we have a method called callMe().

We will see about every basics to handle route in cakephp 4 application in few mins inside this article. Routes can be configured in many ways inside app, like –

  • Normal Routes
  • Named Routes
  • Parameterized Routes
  • Query String in Routes
  • Prefix Routing

Normal Routes in application

We need to create a controller file, a method inside it and then needs to configure route in routes.php file.

Controller can be created at location of [Project]/src/Controller inside CakePHP 4.x. Have a look we have created –

/src/Controller/SampleController.php

<?php

namespace App\Controller;

use App\Controller\AppController;

class SampleController extends AppController
{
    public function initialize(): void
    {
        // constructor method
    }

    public function callMe(){
        $this->autoRender = false; // don't need to create view file
	    $this->set("message", "Very simpl Message");
    }
}

/config/routes.php

$routes->scope('/', function (RouteBuilder $builder) {
  $builder->connect('/call-me', array('controller' => 'Sample', 'action' => 'callMe'));
});

To call this routes, simply back to browser and type – hostname/project-name/call-me. This is an example of simple route, where we don’t need any parameters or passing any query string variable into it.


CakePHP 4 Named Routes

In named routes of application, we provide the name to route. We can call that route by route or by it’s name what we have given to it.

Let’s create a updated route of same controller and it’s action what we have seen above.

$routes->scope('/', function (RouteBuilder $builder) {
   $builder->connect("/call-me", [
        "controller" => "Sample",
        "action" => "callMe"
    ],[
        "_name" => "my-name" // Name to route
    ]);
});  

We can call the above route in 3 different ways –

Called by Controller & Method name

$this->Html->link("Sample Route", [ "controller" => "Sample", "action" => "callMe"]);

Called by Route

$this->Html->link("Sample Route", "/call-me");

Called by Route Name

$this->Html->link("Sample Route", [ "_name" => "my-name"]);

Parametrized Routes of Application

The name itself clears that, passing parameters into routes is called Parameterized routes. Parameters we can pass is of any type, means the value can be a integer, decimal, character, string etc. We can also specify regular expression or value pattern to routes what they accept.

Let’s see how can we configure this –

Pass single value to Route, value can be of any type because we didn’t configure pattern for that.

$routes->scope('/', function (RouteBuilder $builder) {
    $builder->connect("/call-me/{id}", [
        "controller" => "Sample",
        "action" => "callMe"
    ],[
        "pass" => ["id"] // passing variable name used in route
    ]
});

As we can see we have passed the value to URL {id}, it indicates the placeholder of the parameter value. Also we have defined this placeholder into “pass” array. It is important to tell that id placeholder has been used. Here, for now we didn’t configure the value patter for id placeholder, it means we can any value for it.

How can we access this value to controller

Route URL will – hostname/[project]/call-me/12. Here, we have passed an integer value – 12 to id param. To get this value to controller, we will use $this->request->getParam(“[param_name]”);

public function callMe()
{
    $this->autoRender = false;
    // get value from URL
    $id = $this->request->getParam("id");

    echo $id; // it prints 12
}

In this we have configured only for a single parameter value, let’s discuss about multiple values and a specific pattern for placeholders.

Passing multiple values with Pattern

$routes->scope('/', function (RouteBuilder $builder) {
    $builder->connect("/call-me/{id}/{slug}", [
        "controller" => "Sample",
        "action" => "callMe"
    ],[
        "pass" => ["id", "slug"]
    ]
})->setPatterns([
    "id" => "[0-9]+", // it will accept any integer value, no string
    "slug" => "[a-z-]+" // it will accept char, string but no integer
]);

To set patterns for placeholders, we have used the method called setPatterns(). In this method, we put placeholder name with pattern string. Pattern string indicated that, only the specified value will be accepted by that placeholder key.

Also, as we can see we have used 2 placeholders called id and slug.

Accessing value to controller

public function callMe()
{
    $this->autoRender = false;

    $data = $this->request->getParam("pass");

    print_r($data); // to get all data

    //$slug = $this->request->getParam("slug");

    //echo $slug;

    //$id = $this->request->getParam("id");

    //echo $id;
}

Query String Parameter in Route

Query string means we pass values in routes by means using & operator.

Normal URL –

/call-me/12/sanjay-kumar

Query String URL –

/call-me?id=12&slug=sanjay-kumar

How can access this value in Controller?

In the case route configuration will be simple as we did in Normal Route. Have a look, no change in route declaration.

$routes->scope('/', function (RouteBuilder $builder) {
  $builder->connect('/call-me', array('controller' => 'Sample', 'action' => 'callMe'));
});

Accessing this value to Controller

To access query string values, we will use the method of request i.e getQueryParams(). It will list all the values what we have passed at URL as query string params. But in case if we need key wise, then accordingly we should make use of the getQuery() method.

public function callMe()
{
    $this->autoRender = false;

    $all_query_params = $this->request->getQueryParams();

    print_r($all_query_params); // It will print all query string parameters

    echo $all_query_params['id']; // to get single id value from all

    $id = $this->request->getQuery("id");
    echo $id; // getting specific id value from query string

    $slug = $this->request->getQuery("slug");
    echo $slug; // getting specific slug value from query string
}

We hope this article helped you to learn about How To Handle CakePHP 4 Routes in Application Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

1 thought on “How To Handle CakePHP 4 Routes in Application Tutorial”

  1. I think that is among the most important information for me. And i’m satisfied studying your article. However should remark on few general issues, The website style is great, the articles is actually excellent : D. Excellent task, cheers

Comments are closed.