Hướng dẫn mvc folder structure php
IntroductionToday I am going to show how to create a simple PHP application following the MVC pattern (Model-View-Controller). I was inspired by a PHP course I taught some years ago, and in which I built a simple e-commerce with the students. This e-commerce was based on a simple MVC framework based on PHP. Then, people who have continued with code and programming already had a smattering of what means MVC before get their hands on a real framework. Show Nội dung chính
MVC frameworks are widely used in the industry because they offer a lot of advantages for rapid and structured development. There are MVC frameworks for most of the programming languages you may know, from DotNet to PHP. Unfortunately, those frameworks might have a steep learning curve. This is due to the fact that people need to learn how to write code in the framework ecosystem. Personal note: in 2010 I was already developing software for more than 5 years, and I was looking for a good solution in order to build a web application for my boss. Briefing with a former colleague of mine (thanks Davide C.!), I started using Symfony 1.4. I used the “RTFM approach” (Read The Friendly Manual…) before writing any code. In two months I realized a medium-complex application (registration, ACL, dashboard, frontend, etc). After that, I worked on Zend Framework, Symfony 2.0 and 5, and Laravel (currently working on 5.8), and also on microframeworks like Silex (not maintained anymore) and Lumen. Without any doubt, my favorite framework is Laravel. Despite some “magical things” that can scare people, Laravel offers a lot of out-of-the-box features that you can simply activate with the right configuration setting. What does mean MVC?MVC is a design pattern used to decouple data (Models), the user-interfaces (Views), and application logic (Controllers). To be able to follow this “How to”, you need to have a good knowledge of PHP and OOP (Object Oriented Programming). Build a simple PHP MVC frameworkIndependently you are using Docker, XAMPP, or whatever for your development environment, let’s create a simple structure for the simple PHP MVC framework. I use to have a folder called “Solutions” for all my projects, then enter your folder, create a new folder called “simple-php-mvc” and then enter that folder.
Starting small, let’s create the two most important files of our simple PHP MVC: index.php and htaccess. The htaccess configuration fileEnter the public folder, and let’s create a file called index.php Now, at the root level of your project, let’s create a new file called .htaccess
Htaccess is a configuration file for the Apache web server, and the
mod_rewrite directive tells to Apache that every request will end up to the index.php located in the folder named public. What does it mean? It means that if you browse https://simple-php-mvc/page1, https://simple-php-mvc/page2 or https://simple-php-mvc/page3, all of them will end up in the index.php under public, that is the entry point of your PHP MVC framework. This is a big advantage because you can now handle your request in one place, understand what resource is requested
and provide the right response. This is how your project looks like right now:
Bootstrap your PHP MVC frameworkNow you need a way to bootstrap your app and load the code you need. We already said that index.php under the public folder is the entry point, for that reason we include the necessary files from there. First of all, we load the config file, here is the content of index.php:
Now we can create a config.php file under the config folder. Inside the config file, we can store the settings of the framework, for example, we can store the name of our app, the path of the root, and of course, the database connection parameters:
AutoloaderWe want to be able to load the future classes without any pain (see: dozen of include or require), then we’ll use the PSR-4 autoloading with Composer. First, at the root level, you must create a file called composer.json and add the following content:
Then, assuming that you already installed composer on your computer or container, execute the following command (at the root level of your project):
If you check your root folder now, you can see a new folder called vendor that contains the autoload.php file and the composer folder.
From now on, you can use App as a starting point of your namespaces, like this:
Now, let’s learn what the MVC acronym stands for. ModelA model is an object that represents your data. The model will be modeled on your database table structure and it will interact with the database operations (create, read, update and delete).
First of all, let’s create a new folder called Models under app folder. Then let’s create a new file called Product under
Models.
And that’s it. With the methods, you’ll create the objects you need to be filled with the real values based on the model. ViewThe view is responsible to take in the data from the controller and display those values. That’s it. There are a lot of template engines for PHP, from Twig to Blade. For this MVC tutorial for PHP, we’ll use only plain HTML to make things simple. In order to create a new view, we must create a new
file called product.php under the views folder.
The view is now ready to get the product object ($product) and display its values. ControllerThe controller is the heart of the application logic. Is responsible for accepting the input and converting it to commands for the model or view.
Very simple, isn’t it? Obviously, things might be more complex, we can create a parent Controller class, a view method, and other helper functions. But it’s enough for now. The routing systemNow we need a mechanism to deal with the URLs. We want to use a friendly URL; in other words, we want to deal with web addresses that are easy to read and that include words that describe the content of the
webpage. We need a routing system then. First of all, install the component: Install symfony/routing via composer.If you check inside the vendor folder now, you can see that a new folder called Symfony has been created. Let’s start to implement the routing system for our MVC framework then. The goal is to display the values of the product with ID=1 when browsing the URL /product/1
We use Route and RouteCollection classes from the Symfony Routing component in order to create and list all the routes we need. We start with a single product page. Isn’t enough: we must install also this package:
Here some explanation: https://symfony.com/doc/current/components/http_foundation.html
And again from Symfony: In PHP, the request is represented by some global variables ($_GET, $_POST, $_FILES, $_COOKIE, $_SESSION, …) and the response is generated by some functions (echo, header(), setcookie(), …). The Symfony HttpFoundation component replaces these default PHP global variables and functions with an object-oriented layer. OK then, let’s create the routing engine. Add a new file called Router.php inside your app folder and put this code inside it:
The code is straightforward and speaks for itself, but let’s explain it a bit: the URL matcher takes in the request URI and will check if there is a match with the routes defined in routes/web.php. If there is a match, the function call_user_func_array will do the magic, calling the right method of the right controller. Now we can include the routes system in the index.php file:
Now that we prepared the routing system, we can browse /product/1 page and see the result. Obviously, the values are now empty. Let’s add some fake values to the product (inside ProductController.php):
And browse again the page /product/1 You can now add your database connection, and return the values from the database, using a raw query or an ORM like Doctrine or Eloquent. Additional notes to the routing: your routes could overlap with each other, for example, if you write /{pageSlug} before any other route, such as /register. You can easily overcome this problem simply by writing your general route /{pageSlug} at the end of all the routes. This route will become your fallback. Or, another solution is to add a prefix, such as /static/{pageSlug} or /public/{pageSlug}. The homepageLet’s prepare now the homepage route. Open the routes/web.php and add the new route:
Obviously, we need to create the new controller PageController:
And the new view:
Since we use the same code for the header and footer, we can create a layout folder and separate the code for those pieces of HTML. In order to navigate the page, open your browser and browse this URL:
The exact URL depends on your settings. I use Docker for my local environment, and I usually set up the port, then my URL could be slightly different from yours, for example, I use
Note: if you installed your project into a subfolder as many users seem to do, you must set up URL_SUBFOLDER constant in the config file. For example, if you installed this project inside a subfolder called simple-mvc-php-framework, your final URL will be:
Improve the PHP MVC frameworkDatabase connection and ORM, session, cookies, better page controller that accept different page parameters, or any other feature can be added very easily, but this article wants to show only the way to build a really simple PHP MVC. Download the codeYou can download the zip file, or clone the code of this article via Github. ConclusionOnce you’re getting confident with the MVC paradigm, I suggest reading the documentation of Laravel (my favorite PHP MVC framework) or Symfony and start to get your feet wet! You’ll notice that the development becomes faster than use a pure PHP solution. Thanks for your time, I hope you got some new information about the MVC paradigm. Feel free to fork the project on GitHub, and if you have any issues, check the issues tab or open a new one (if it is a real new one!). Anyway, you can also send me a message but I prefer to answer on Github in order to share the knowledge with other people. I decided to close the comments on this page due to the huge amount of spam, and the huge amount of duplicated questions. I hope you can understand! Note: this project is a simple starter kit, and it works well if your environment is correctly configured. I don’t use XAMPP, or another pre-configured stack package. In the past I used to create my LAMP installing the software individually, now I am using Docker. Then if you have some issue with your environment, it’s up on you to solve your issue. And again: this is a simple starter kit with the goal of helping people to understand some concepts behind the MVC. If you want to create a professional project, go for Laravel or Symfony. Can you use PHP in MVC?Traditional PHP applications that follow application design best practices can be ported to MVC frameworks with minimal modifications. What is MVC in PHP w3schools?MVC is abbreviated as Model View Controller is a design pattern created for developing applications specifically web applications. Why MVC is used in PHP?MVC allows you to separate your business logic from your presentation layer. This "Separation of Concerns" allows you to quickly find and edit portions of your code. It also enables easy reuse of your UI components across your system. What is MBC PHP?MBC to PHP rate today is ₱0.00025942 and has increased 6.6% from ₱0.000243414516 since yesterday. MicroBitcoin (MBC) is on a downward monthly trajectory as it has decreased -0.8% from ₱0.000261430871 since 1 month (30 days) ago. |