CakePHP 4 How To Use Prefix Routing Tutorial

Reading Time: 6 minutes
3,334 Views

Inside this article we will see CakePHP 4 How To Use Prefix Routing. Article contains very classified information about prefix routing as well as reading parameters values from prefixed URLs in CakePHP application.

Examples of Prefixed Routes are –

/admin
/admin/hello
/shop
/shop/add-product
/shop/product-detail/1001
/shop/product?name=xxxx&cost=yyyy

Here, you can see prefixed routing. Route contains prefix for admin and shop. This is only for understanding, you can assume your own routes. You can read values from prefixed routes like for parameterized routes, query string values.

Also while working with prefix routing we need to take care of Controller & Template files folder location. If they don’t set proper then you may not access prefix routes as per your need.

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.

Prefix Routes Concept

Suppose we have routes prefixed as –

/admin/
/admin/hello

You can see we have two routes uses prefix /admin. Here, you need to understand the folder structure of controller and templates very carefully.

Folder location of Controller

Responsible controller to handle these routes should be placed within Admin folder. So complete location will be like /src/Controller/Admin/<YourController>

Folder location of Templates

What view templates you will use for your controller’s actions should be placed inside Admin folder as well. Complete path for templates as /templates/Admin/<YourController>/<action_name>.php

Create Prefix Routes

Open routes.php file from /config folder. Add these routes into it.

//...

$routes->prefix('Admin', function (RouteBuilder $builder) {
    $builder->scope('/', function (RouteBuilder $builder) {
        $builder->connect("/", ["controller" => "User", "action" => "index"]);
        $builder->connect("/hello", ["controller" => "User", "action" => "helloAction"]);
    });
});

$routes->prefix('Shop', function (RouteBuilder $builder) {
    $builder->scope('/', function (RouteBuilder $builder) {
        $builder->connect("/", ["controller" => "Product", "action" => "index"]);
        $builder->connect("/add-product", ["controller" => "Product", "action" => "addProduct"]);
    });
});

//...

We have two prefix for routes as /admin and /shop.

For admin prefix routes are –

/admin
/admin/hello

For shop prefix routes are –

/shop
/shop/add-product

Let’s create controllers.

Create Controllers

Open project into terminal and run this console commands.

$ bin/cake bake controller User --no-actions --prefix Admin

It will create few files. One file is of controller file. File UserController.php will be created inside /src/Controller/Admin folder. While creating controller file also it creates a Admin folder first due to –prefix flag.

$ bin/cake bake controller Product --no-actions --prefix Shop

It will create few files. One file is of controller file. File ProductController.php will be created inside /src/Controller/Shop folder. While creating controller file also it creates a Shop folder first due to –prefix flag.

Open UserController.php and write this code into it.

<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Controller\AppController;

class UserController extends AppController
{
    public function index()
    {
        // Template file: /templates/Admin/User/index.php
    }

    public function helloAction()
    {
        // Template file: /templates/Admin/User/hello_action.php
    }
}

Open ProductController.php and write this code into it.

<?php
declare(strict_types=1);

namespace App\Controller\Shop;

use App\Controller\AppController;

class ProductController extends AppController
{
    public function index()
    {
        // Template file: /templates/Shop/Product/index.php
    }

    public function addProduct()
    {
        // Template file: /templates/Shop/Product/add_product.php
    }
}

Create Template Files

Create two folders for two created controllers. But before that we need to create prefix folder first. Create Admin & Shop folder into /templates folder.

Next,

Create controller folders. User and Product will be two controller folder. So for User controller it will be inside /templates/Admin/User and for Product it will be as /templates/Shop/Product

In UserController, we have two methods as index() and helloAction() need to create two templates inside /templates/Admin/User – index.php and hello_action.php

In ProductController, we have two methods as index() and addProduct() need to create two templates inside /templates/Shop/Product – index.php and add_product.php.

Working with Route Parameters

For prefixed routes let’s say we have these routes.

/admin/hello/34

In terms of route, you need to add these settings

$builder->connect("/hello/{id}", [
    "controller" => "User", 
    "action" => "helloAction"
], [
  "pass" => ["id"]
]);

Inside UserController.php, you can use this method to get route values.

echo $this->request->getParam("id");

Working with Query String Params

URL be like

/admin/hello?name=sanjay&email=sanjay@gmail.com

Inside UserController.php, you can use this method to get route query string value. To read values

// Reading all query string parameters
$queryParams = $this->request->getQueryParams();
print_r($queryParams);

We hope this article helped you to learn about CakePHP 4 How To Use Prefix Routing 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.