Welcome Guest, Not a member yet? Register   Sign In
URI Routing: Why my controllers function does'nt care about the defaults?
#1

[eluser]F. Albrecht[/eluser]
Hi all,

I'm just porting a procedural PHP project to CI and it rocks. The code is cleaner, compacter, better to read and will scale in the future...

At the moment I have one question about URI routing:

Code:
$route['(my_link)/?(:any)?/?'] = "my_controller/my_function/$1/$2";

In my_controller.php:

Code:
function my_function($foo, $bar = 'foo')
{
    echo "bar = " . $bar;
}

The link

Code:
www.domainname.tld/index.php/my_link/12

generates

Quote:bar = 12

The link

Code:
www.domainname.tld/index.php/my_link

generates

Quote:bar =

but should generate

Code:
bar = foo


A vardump via

Code:
var_dump($bar);

says

Quote:string(0) ""

What happens to my 'foo'? Anything wrong with my route/logic/code?

I guess that a possible workaround this

Code:
if ( !empty($this->uri->segment(2)) ) make foo else make bar

or this

Code:
if ( !empty($bar)) ) make foo else make bar

snippet is?

Thanks for reading!
#2

[eluser]wiredesignz[/eluser]
Empty segments never appear to be empty, they probably contain FALSE, in any case I always test like so:

$var = $this->uri->segment(2) OR $var = 'something';
#3

[eluser]F. Albrecht[/eluser]
Hi wiredesignz,

thanks a lot.

I've noticed yesterday that the default parameter is/are valid, if I DON'T route any of the NEEDED default parameter(s) to the controller via routes.php. This works:

Code:
$route['test/?(.*)?/?'] = "page_controller/my_test";

Code:
function my_test($bar1 = 'foo1', $bar2 = 'foo2')
    {
        echo "bar1 = $bar1<br>";
        echo "bar2 = $bar2";

    }

And I can combine both methods:

Code:
$route['test/?(.*)?/?'] = "page_controller/my_test/$1";

Code:
function my_test($CIpassed,$bar1 = 'foo1', $bar2 = 'foo2')
    {
        echo "CIpassed = $CIpassed<br>";
        echo "bar1 = $bar1 <br>";
        echo "bar2 = $bar2";
    }

If I add a tailing slash in

Code:
$route['test/?(.*)?/?'] = "page_controller/my_test/$1/";

the next segment will be set empty through CI.


At the moment I'm not able to recognize the benefits of any of these ways. Perhaps the combination of both to mark down more complex routes...


What do you think?


Edith says: I've just played a little bit the routes and it seems to be that everything is possible. Another variante, especially in view to a generic controller for unlimited hierarchic "static" sites:

Code:
$route['(.*)/?'] = "page_controller/my_test/$1";

Code:
function my_test($CIpassed,$bar1 = 'foo1', $bar2 = 'foo2')
    {
        echo "CIpassed = $CIpassed<br>";
        echo "bar1 = $bar1 <br>";
        echo "bar2 = $bar2";
    }

Then you have only to set the exceptions for individual controllers like gallery, blog etc. in routes.php...




Theme © iAndrew 2016 - Forum software by © MyBB