Tutorials on Generating URLs in CakePHP

Generating URLs in CakePHP

This is a cool feature of CakePHP. Using the generated URLs, we can easily change the structure of URL in the application without modifying the whole code.

url( string|array|null $url null , boolean $full false )

The above function will take two arguments −

  • The first argument is an array specifying any of the following − ‘controller’, ‘action’, ‘plugin’. Additionally, you can provide routed elements or query string parameters. If string, it can be given the name of any valid url string.
  • If true, the full base URL will be prepended to the result. Default is false.

Example

Make Changes in the config/routes.php file as shown in the following program.

config/routes.php

<?php use CakeCorePlugin; 
use CakeRoutingRouteBuilder; 
use CakeRoutingRouter; 
Router::defaultRouteClass('DashedRoute'); 
Router::scope('/', function (RouteBuilder $routes){ $routes->connect('/generate',
['controller'=>'Generates','action'=>'index']); }); 
Plugin::routes();

Create a GeneratesController.php file at src/Controller/GeneratesController.php. Copy the following code in the controller file.

src/Controller/GeneratesController.php

<?php namespace AppController; 
use AppControllerAppController; 
use CakeORMTableRegistry; 
use CakeDatasourceConnectionManager; 
class GeneratesController extends AppController{ public function index(){ } } ?>

Create a folder Generates at src/Template and under that folder create a View file called index.ctp. Copy the following code in that file.

src/Template/Generates/index.ctp

This is CakePHP tutorial and this is an example of Generating URLs.

Execute the above example by visiting the following URL −

http://localhost:85/CakePHP/generate