5
votes

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

2
The (.*) are greedy (i.e. they extend as much as possible). In this case, you'll have to use (.*?) for the first two. It gives you RewriteRule ^(.*?)/(.*?)/(.*)$ index.php?model=$1&view=$2&parameters=$3 [L,NS]instanceof me

2 Answers

11
votes

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.

3
votes

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.