开发者

URL routing in an MVC framework - PHP

I'm developing an MVC framework in PHP from scratch; mostly for the learning experience but this could easily end up in a live project. I went through this tutorial as a base and I've expanded from there.

Requests are made like this:

examplesite.com/controller/action/param1/param2/ and so on...

A开发者_Python百科nd this is my .htaccess file:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]

So all requests go to index.php and they are routed to the correct controller and action from there. If no controller or action is given, then the default 'index' is assumed for both.

I have an index controller with an index action, which is supposed to be the home page of my site. I can access it by going to examplesite.com (since the index part is assumed). It has some images, a link to a stylesheet, and some scripts. They are linked with paths relative to index.php. I thought this would be fine since all request go to index.php and all content is simply included in this page using php. This works if I go to examplesite.com. I will see all of the images and styles, and scripts will run. However, if I go to examplesite.com/index, I am routed to the correct part of the site, but all of the links don't work. Does the browser think I am in a different folder?

I would like to be able to use relative paths for all of the content in my site, because otherwise I need to use absolute paths everywhere to make sure things will show up. Is this possible?


You need an absolute path, because browsers evaluate the relative paths relative to the current request uri (unless you use the base tag, see below). Mind you though that an absolute path doesn't necesseraly mean you need to include the domainname in it. Simply starting with a forward slash is enough. It's the absolute path relative to the server, so to speak.

So:

<img src="/images/bla.gif">

in stead of

<img src="images/bla.gif">

...will work just fine.

As I've mentiond, another approach would be to use the base tag. But for reasons I can't remember right now, I believe it is recommended to not use it. (If anybody else wants to chime in here...)


IMO images, javascript, styles, and other static content should not be part of the routing system. It means you load PHP for every request (a performance whack), when Apache could serve those files just fine.

My .htaccess always lets existing files skip PHP:

# Files with an extension that exist are served up straight.
RewriteCond %{REQUEST_URI} \..+$
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .* - [L]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜