Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple MVC mod-rewrite

I'm not sure how to do a mod-rewrite for a modular MVC structure. What I want to happen is the URL captures:

http://domainname.com/index.php?model={model}&view={view}&parameters={parameters}

NOTE: parameters will be in a specific order and separated by pipes (unless there is a better way): parameters=param1|param2|param3

http://domainname.com/{model}/{view}/{parameters}

Example:

http://domainname.com/faq/edit/13

Another Example:

http://domainname.com/faq/index/{sort}/{page}/{search} http://domainname.com/faq/index/asc/3/How+to

Essentially anything after the model and view will and can be parameters; as many as needed. For each view I will know the possible parameters that area allowable and in what order.

Thank you in advance.

--

Using the code below this is what I have:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)/(.*) index.php?model=$1&view=$2&parameters=$3 [L,NS]

URL: http://localhost:8888/testing/faq/index/asc/5/How+to
PHP $_GET variables:

Array
(
    [model] => faq/index/asc
    [view] => 5
    [parameters] => How to
)

Should be:

Array
(
    [model] => faq
    [view] => index
    [parameters] => asc/5/How to
)

Please help

like image 611
Torez Avatar asked Jun 13 '09 17:06

Torez


2 Answers

You could use a PHP function to do that. Quickly, with no default value or error handling:

list( $controller, $function, $params ) = explode( '/', $uri, 3 );
$params = explode( '/', $uri );

And in the .htaccess, redirect any non-existing query to your PHP query-handling file:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ mvc.php [L,NS]

Beware to filter your input though, not to include any file, etc.

like image 187
instanceof me Avatar answered Nov 20 '22 12:11

instanceof me


You could also have your htaccess like this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)/(.*) mvc.php?model=$1&view=$2&parameters=$3 [L,NS]

This is just another way to do it, although personally I prefer streetpc's way.

like image 36
rogeriopvl Avatar answered Nov 20 '22 13:11

rogeriopvl