MVC的利与弊

来源:互联网 发布:淘宝ipad版下载 编辑:程序博客网 时间:2024/04/29 03:46

原文:MVC pattern pros and cons

MVC pattern pros and cons

PHP, programming

In this post I'll talk about some of the pros and cons of the MVC (model-view-controller) pattern I've come across, concentrating in the Zend Framework implementation of it.

For those who don't know what the MVC pattern is... It basically is a way of structuring PHP code, data storage and HTML code in separate files. "Model" is the data/data access code, "View" is the HTML code or things such as Smarty templates and "Controller" parses the user requests, fetching information from models, assigning that to views and displaying views etc. For a thorough look, I suggest reading the Wikipedia article on MVC.

Cons

The first thing that you notice with Zend Framework is probably the suggested "application directory structure", which goes something like this:
/www/application/controllers                /views    /library/Zend            /MyLib
Compare that to some quick 'n' dirty directory structure:
/www
Hmm... So you need that many more directories to begin with.
Then there is the whole controller approach: You need to define a class for every controller and in a separate file, too. Every action in a controller is a function, which doesn't differ much from some simpler approaches where you write a function different things that happens.
Also, there are the templates... The HTML code is separated to the views directory from the rest.
So that makes for a lot of files and some more code.
Springing from the ZF file structure is also a slight file inclusion overhead. As most Zend Framework classes are in separate files and there are quite many of them, the code often has to include many different files and that may cause some slowdown especially on very busy sites.

Pros

Sites made with MVC pattern are a lot easier to maintain.
After you get used to the directory and file structure used, it's much cleaner than dumping all functions and stuff into a single file.
The separation of PHP code from the templates also makes it easy to change site layout and such without breaking any functionality.
Well written MVC applications are also quite modular. You can reuse components from old sites in new ones.

Conclusion


Pros:
- Easy to maintain
- Easy to extend
- Easy to reuse

Cons:
- A lot of files and directories
- Requires some more code to get started

From this it could be said that the MVC pattern isn't for very small projects. However, I think the pros greatly outweigh the cons for anything except the very smallest sites.

原创粉丝点击