Welcome Guest, Not a member yet? Register   Sign In
optional parameters in route definition
#1

Hello everyone. I am trying to create a route with 2 parameters. The first being mandatory and the second being optional. I've gone through all the documentation but I don't see any section that talks about this. So my question is how to do it.

For the moment I had to create 2 routes

PHP Code:
$routes->addPlaceholder([
    'version' => 'master|\d+\.(?:\d+|x(?:\-dev)?)',
    'page' => '[a-z0-9-]+',
]);
$routes->get('docs/(:version)', [DocsController::class, 'show']);
$routes->get('docs/(:version)/(:page)', [DocsController::class, 'show']); 


But I would like to have only one route like:

PHP Code:
$routes->get('docs/(:version)/(:page)?', [DocsController::class, 'show']); 


So far it doesn't seem to exist Confused
Reply
#2

I would manage like this
routes.php
PHP Code:
$routes->get('docs/(:any)/(:any)''DocsController::show/$1/$2'); 


Controller method
PHP Code:
public function show(string $versionstring $page '')
{
    // your code

Reply
#3

Yes, there is no optional parameters.
Reply
#4

(This post was last modified: 08-30-2023, 02:16 AM by Dimtrovich.)

(08-29-2023, 10:27 AM)davis.lasis Wrote: I would manage like this
routes.php
PHP Code:
$routes->get('docs/(:any)/(:any)''DocsController::show/$1/$2'); 


Controller method
PHP Code:
public function show(string $versionstring $page '')
{
    // your code


Indeed, it is a good alternative. The problem I have with this is that by using the *any* placeholder, any string will be allowed in the URL and therefore can possibly generate an error at the controller level. Unless I first test the parameters received by my controller method before really starting my business logic.
I will keep the use of 2 routes, knowing that the 2nd parameter of my controller method is optional. There at least I know that the URL verification will be managed by CodeIgniter.

PS: In general, I am very restrictive, I prefer to define strong routing (without the auto router and using strict regex)

(08-29-2023, 08:55 PM)kenjis Wrote: Yes, there is no optional parameters.
Don't you think it would be interesting to have it? There are multiple use cases that may require it.

The solution could be using the AutoRouter or using the "_remap" method but having strict defined routes is more secure in my opinion
Reply




Theme © iAndrew 2016 - Forum software by © MyBB