Chapter 6. Adapting to MVC

Web applications are more complex than what we have built so far. The more functionality you add, the more difficult the code is to maintain and understand. It is for this reason that structuring your code in an organized way is crucial. You could design your own structure, but as with OOP, there already exist some design patterns that try to solve this problem.

MVC (model-view-controller) has been the favorite pattern for web developers. It helps us separate the different parts of a web application, leaving the code easy to understand even for beginners. We will try to refactor our bookstore example to use the MVC pattern, and you will realize how quickly you can add new functionality after that.

In this chapter, you will learn the following:

  • Using Composer to manage dependencies
  • Designing a router for your application
  • Organizing your code into models, views, and controllers
  • Twig as the template engine
  • Dependency injection

The MVC pattern

So far, each time we have had to add a feature, we added a new PHP file with a mixture of PHP and HTML for that specific page. For chunks of code with a single purpose, and which we have to reuse, we created functions and added them to the functions file. Even for very small web applications like ours, the code starts becoming very confusing, and the ability to reuse code is not as helpful as it could be. Now imagine an application with a large number of features: that would be pretty much chaos itself.

The problems do not stop here. In our code, we have mixed HTML and PHP code in a single file. That will give us a lot of trouble when trying to change the design of the web application, or even if we want to perform a very small change across all pages, such as changing the menu or footer of the page. The more complex the application, the more problems we will encounter.

MVC came up as a pattern to help us divide the different parts of the application. These parts are known as models, views, and controllers. Models manage the data and/or the business logic, views contain the templates for our responses (for example, HTML pages), and controllers orchestrate requests, deciding what data to use and how to render the appropriate template. We will go through them in later sections of this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.183.10