A free and open-source book on Zend Framework for beginners


4.2. Separating Business Logic from Presentation

A typical website has three kinds of functionality: code implementing business logic, code implementing user interaction and code rendering HTML pages (presentation). Before PHP frameworks, programmers usually merged these three types of code in a single big PHP script file, which made it a pain to test and maintain such code, especially when you write a large website.

Since that time, PHP became object-oriented, and now you can organize your code into classes. The Model-View-Controller (MVC) pattern is just a set of advices telling you how to organize your classes in a better manner, to make them easy to maintain.

In MVC, classes implementing your business logic are called models, code snippets rendering HTML pages are called views, and the classes responsible for interacting with user are called controllers.

Views are implemented as code snippets, not as classes. This is because views are typically very simple and contain only the mixture of HTML and inline PHP code.

The main objective of the MVC concept is to separate the business logic (models) from its visualization (views). This is also called the separation of concerns, when each layer does its specific tasks only.

By separating your models from views, you reduce the number of dependencies between them. Therefore, changes made to one of the layers have the lowest possible impact on other layers. This separation also improves the code reusability. For example, you can create multiple visual representations for the same models (changeable themes).

To better understand how this works, lets remember that any website is just a PHP program receiving an HTTP request from the web server, and producing an HTTP response. Figure 4.2 shows how an HTTP request is processed by the MVC application and how the response is generated:

Figure 4.2. HTTP request processing in an MVC web application Figure 4.2. HTTP request processing in an MVC web application

Now you might have some idea how models, views and controllers cooperate to generate HTML output. In the next sections, we describe them in more details.


Top