Multiple Variables In Function

Hi! Sorry for my english.

Can I pass multiple variables to a function in a controller?

For example in a classified page I need this:

domain.com/shops/spain -> shows the shops in spain

I can solve this situation with a function in a controller

[b]controller Shops…{

function index($country){}

}[/b]

But I don’t know how solve this:

domain.com/shops/spain/valencia -> shows the shops in valencia

this is wrong?

[b]controller Shops…{

function index($country,$state){}

}[/b]

And what about:

domain.com/shops/valencia

domain.com/shops/toys/spain

domain.com/shops/toys/spain/valencia

Maybe the solution is using a urlmanager but I have too many controllers.

Thanks!

You can make one or more of the parameters optional by setting a default value for them:




public function actionIndex($country,$state = null)



Or you can have multiple actions:




public function actionCountry($country)


...


public function actionState($state)



Please see the guide about controller actions and URL management.

Thanks for answering Rodrigo.

The default value seems very useful in this case.

But I have multiple combinations:

domain.com/shops/ -> show all shops

domain.com/shops/toys -> show all toy shops

domain.com/shops/spain-> show shops in spain

domain.com/shops/spain/valencia-> show shops in valencia

domain.com/shops/toys/spain -> show toy shops in spain

domain.com/shops/toys/spain/valencia -> show toy shops in valencia

How can I know if the second parameter is a $subcategory (toys) or a $country (spain)? and the rest of parematers? looking at the DB maybe for every case, 1 parameter, 2, 3…?

Seems very ugly this way.

Thanks!

Due to your URL structure, you will probably need a custom URL Rule to check on the database whether the the request is for a category or a location.

You can take a look at dburlmanager for inspiration.

Hi Kitune

An easy way is to call the controller/action by pass only the first parameter.

In the function check for the other parameters (if they exist) and act accordingly (may calling other function with appropriate parameters)

If you want friendly url see the post of Rodrigo Coelho

Yes, this was my first approach adding a "Finder" controller first.

domain.com/finder/shops/ -> show all shops

domain.com/finder/shops/toys -> show all toy shops

domain.com/finder/shops/spain-> show shops in spain

domain.com/finder/shops/spain/valencia-> show shops in valencia

domain.com/finder/shops/toys/spain -> show toy shops in spain

domain.com/finder/shops/toys/spain/valencia -> show toy shops in valencia

My index function of the Finder Controller checks for the first parameter, check if there is a second parameter, etc. But it seems very "handmade".

Custom url rule seems a nice idea, I’ll try it. thanks!

You’re welcome. Please post again in case you need further clarifications while implementing the custom URL rule.