Best way to load only specfic functions in PHP
I'm writing my own content management system for a personal website, it's going to be low traffic, but I'd like to use the best practices for my future knowledge.
My plan is to have separate sections, basically the first non-root directory, will have it's own script and will directly control all its subpages. I want everything to be controlled from a 开发者_运维技巧index.php in the root dir using mod_rewrite to make this transparent.
What would be the best way to load only what is needed for that section and not every other section as well? I was thinking about using a separate file for each section and naming it based on the URL that I'm using so I can include only that. But that hardly seems elegant. Is there a better way to accomplish this?
Have a look at the MVC pattern and the Front Controller pattern. This can be implemented in a number of ways with very varied complexity. Basically, your FrontController will accept any incoming requests and dispatch them to the appropriate controllers (your sections). Your controllers will then fetch any data from your model, e.g. your business objects and push them to the view. The view is what gets send back to the client.
In addition to the MVC pattern that Gordon mentioned, to make sure you aren't loading any extra classes that you don't need to use you can setup a simple class autoloader. The autoloader can work a number of ways, but in the MVC app I'm currently working on, the class name is also the name of the file, and it dictates where the file is located also.
__autoload is a magic method that PHP calls if you attempt to access a class that is currently not included. Then it performs whatever action is specified in the function then attempts the same call to that class again. Implementing an autoloader cut the average memory footprint of an instance of my MVC app by about 75%... check out the documentation here:
http://us3.php.net/autoload
Well what you normally see is that the rewrite rule is going to either just do a flat erwrite to /index.php - this will then somoehow envoke some functions/classes that are going to sort out what the desired endpoint (a controller) is and what the parameters for that endpoint are. so then you would in that controller (say /mysection/index.php) you would set up all the resources and invoke all the stuff that needs to be invoked to display a given page for the section.
精彩评论