Linas
Linas

Reputation: 4408

Load default action and controller if none were found

I'm not sure if it's possible, but what i need is to load default controller and action if specified controller has not been found from the url, so let's say if i have this url:

http://mywebsite.com/john

It would have to call user controller and selected_user action,

And if i have url http://mywebsite.com/pages/profile

it would have to call pages controller and profile action because both has been specified and found

Is there a way to do it?

I am using Kohana 3.2

EDIT Here is my htaccess:

# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /ep/

# Protect hidden files from being viewed
<Files .*>
    Order Deny,Allow
    Deny From All
</Files>

# Protect application and system files from being viewed
RewriteRule ^(?:application|modules|system)\b.* index.php/$0 [L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]

/ep is my directory in htdocs also i did set 'base_url' => '/ep/', in my bootstrap as well

Upvotes: 0

Views: 557

Answers (1)

AlexP
AlexP

Reputation: 9857

Assuming mod_rewriting is enabled and the .htaccess file is configured correctly. All you need to do is specify a new route within the bootstrap, after the current default one.

For example:

<?php

  Route::set('default', '(<controller>(/<action>(/<stuff>)))', array('stuff' => '.*'))
    ->defaults(array(
        'controller' => 'welcome',
        'action' => 'index',
  ));

  /** Set a new route for the users **/
  Route::set(
    "users", "<name>", array("name" => ".*")
  )->defaults(array(
    'controller' => 'users',
    'action' => 'selected_user'
  ));

  /** Within the selected_user method you can then check the request for the "name" 
    validate the user parameter (parhaps against the db) and then again route the correct
    pages/profile if found

    e.g.
  **/

  $username = $this->request->param('name');
  if ($username == "alexp") {
    /** reroute to the users/profile controller with data **/
  }

?>

Edit: also I forgot to mention that the above routes will be called for anything after the base Uri so "http://mysite.com/john" and "http://mysite.com/89s88" will also try to use that route. You could imagine allot of routes being needed over time, so best at least stick to a minimum of /controller/action varieties or you may other wise find yourself with some complicated regex in the routes where it is unneeded.

Upvotes: 1

Related Questions