wwhitewalter
wwhitewalter

Reputation: 47

Understanding Cake PHP routes

I'm coming from Laravel and now I have a work to do based on Cake 3. I need an help to understanding routing. The application uses CRUD to generate API for a Angular5 app. The routes.php php is this:

    <?php
/**
 * Routes configuration
 *
 * In this file, you set up routes to your controllers and their actions.
 * Routes are very important mechanism that allows you to freely connect
 * different URLs to chosen controllers and their actions (functions).
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
use Cake\Routing\Route\DashedRoute;

Router::defaultRouteClass(DashedRoute::class);

Router::extensions(['json', 'xml']);

Router::scope($baseScope, function ($routes) {

    $routes->connect('/', ['controller' => 'App', 'action' => 'welcome']);
    $routes->connect('/getConfig', ['controller' => 'App', 'action' => 'getConfig']);

    $routes->fallbacks('DashedRoute');
});

/**
 * Load all plugin routes.  See the Plugin documentation on
 * how to customize the loading of plugin routes.
 */
Plugin::routes();

I need to know which method for example, respond to users/add route.... Inside the user controller I didn't get any add method...

Upvotes: 0

Views: 503

Answers (1)

Manohar Khadka
Manohar Khadka

Reputation: 2195

It's obvious to get confusion with routing if you are came from Laravel.

CakePhp's routing is different but easier with Laravel routing in some ways.

In Laravel you have to define route for every method of the controller with the request type (get,post) just as you know.

But In CakePhp you don't need to write route for every method of the controller if you would like to go with CakePhp's conventions.

If your controller is UsersController and method is add, By CakePhp convention route will be 'users/add'.

Similarly,

Controller: Articles, Method:index => route: articles/index
Controller: Articles, Method:view_user_data => route: articles/view-user-data

More Here: https://book.cakephp.org/3.0/en/development/routing.html

Also look at the power of cakephp conventions: https://book.cakephp.org/3.0/en/intro/conventions.html

Upvotes: 1

Related Questions