thatidiotguy
thatidiotguy

Reputation: 9011

Kohana Routing (and Rerouting) Issue

I am using PHP 5.5 and Kohana 3.3

I am developing a website structure that always has the language preference of the user as the first "item" of a uri.

For example:

mydomain.com/en/products mydomain.com/de/store

Now, I am sure that some users will try and be clever and type things in like:

mydomain.com/products

which is fine, I just would like them to be rerouted to

mydomain.com/en/products to keep everything consistent.

The code I have below is working as long as the uri has only one "directory" in the URI e.g.

mydomain.com/products

mydomain.com/store

but not for uris like down further subdirectories like:

mydomain.com/products/something mydomain.com/store/purchase/info

Here are my routes:

Route::set('home_page', '(<lang>)')
    ->defaults(array(
        'controller' => 'Index'
    ));

Route::set('default', '(<lang>(/<controller>(/<action>(/<subfolder>))))')
    ->defaults(array(
        'controller' => 'Index',
        'action' => 'index'
    ));

Here is the code in my parent controller that every other controller inherits from:

public function before()
        {           
            $this->uri = $this->request->uri();

            $this->lang = $this->request->param('lang');

            //If user directly inputted url mydomain.com without language information, redirect them to language version of site
            //TODO use cookie information to guess language preferences if possible
            if(!isset($this->lang))
            {
                $this->redirect('en/', 302);
            }

            //If the first part of path does not match a language redirect to english version of uri
            if(!in_array($this->lang, ContentManager::getSupportedLangs()))
            {
                $this->redirect('en/'.$this->uri, 302);
            }
          }

Upvotes: 0

Views: 313

Answers (1)

Jonathan
Jonathan

Reputation: 1089

You could replace the two routes given with this one:

Route::set('default', '(<lang>/)(<controller>(/<action>(/<subfolder>)))',
array(
    'lang' => '(en|fr|pl)'
))
->defaults(array(
    'controller' => 'Index',
    'action' => 'index'
));

where the string (en|fr|pl) is the concatenation of your supported languages, i.e. '('.implode('|', ContentManager::getSupportedLangs()).')'.

If this solution remains obscure I'm happy to explain it in more detail but I hope you can see on reflection that your problem arose because your first route, home_page, was being matched by e.g. mydomain.com/products.

Your controllers' before() function should be revised as well. The redirects won't work as things stand because you're going to end up redirecting to e.g. en/ru/Index. So why not keep it simple and use:

    public function before()
    {           
        $default_lang = 'en';
        $this->lang = $this->request->param('lang', $default_lang);
    }

Upvotes: 1

Related Questions