


Use Composer to build your own PHP framework design MVC, composermvc_PHP tutorial
Use Composer to build your own PHP framework design MVC, composermvc
Review
In the previous tutorial, we used the codingbean/macaw Composer package to build two simple routes. The first one responds to GET ‘/fuck’, and the other one will hold all requests. In fact, for the PHP framework, everything is possible with routing. So the next thing we have to do is to make the MFFC framework more standardized and fuller.
This involves another value of the PHP framework: establishing development specifications to facilitate multi-person collaboration, and using tools such as ORM and template engines to improve development efficiency.
Officially start planning folders
Create a new MFFC/app folder, create three folders: controllers, models, and views in the app, and officially start the journey of MVC.
(Who said I copied Laravel? I obviously copied Rails :-D)
Use namespaces
New controllers/BaseController.php file:
<?php<br />/**<br />* BaseController<br />*/<br />class BaseController<br />{<br /> <br /> public function __construct()<br /> {<br /> }<br />}<br />
New controllers/HomeController.php file:
<?php
/**<br />* \HomeController<br />*/<br />class HomeController extends BaseController<br />{<br /> <br /> public function home()<br /> {<br /> echo "<h1>控制器成功!</h1>";<br> }<br>}
Add a route: Macaw::get('', 'HomeController@home');`, open the browser and directly access http://127.0.0.1:81/`, the following prompt will appear:
Fatal error: Class 'HomeController' not found in /Library/WebServer/Documents/wwwroot/MFFC/vendor/codingbean/macaw/Macaw.php on line 93
Why is the HomeController class not found? Because we did not allow it to load automatically, modify composer.json to:
{<br> "require": {<br> "codingbean/macaw": "dev-master"<br> },<br> "autoload": {<br> "classmap": [<br> "app/controllers",<br> "app/models"<br> ]<br> }<br>}
Run composer dump-autoload`, wait a moment, refresh, you will see the following content (don’t forget to adjust the encoding~):
Congratulations, you have successfully used the namespace!
Connect to database
Create a new models/Article.php file with the following content (please change the database password yourself):
<?php
/**
* Article Model
*/
class Article
{
public static function first()
{
$connection = mysql_connect("localhost","root","password");
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
mysql_set_charset("UTF8", $connection);
mysql_select_db("mffc", $connection);
$result = mysql_query("SELECT * FROM articles limit 0,1");
if ($row = mysql_fetch_array($result)) {<br /> echo '<h1>'.$row["title"].'</h1>';<br> echo '<p>'.$row["content"].'</p>';<br> }
mysql_close($connection);<br> }<br>}
Modify controllers/HomeController.php file:
<?php/*** \HomeController*/class HomeController extends BaseController{ public function home() { Article::first(); }}
Refresh, at this time you will get the information that the Article class is not found, because we have not updated the automatic loading configuration:
composer dump-autoload
While waiting, we create the database mffc`, create the table articles` in it, design two fields title` and `content to record information, and fill in at least one piece of data. You can also run the following SQL statement after creating the mffc database:
DROP TABLE IF EXISTS `articles`;<br />CREATE TABLE `articles` (<br /> `id` int(11) unsigned NOT NULL AUTO_INCREMENT,<br /> `title` varchar(255) DEFAULT NULL,<br /> `content` longtext,<br /> PRIMARY KEY (`id`)<br />) ENGINE=InnoDB DEFAULT CHARSET=utf8;<br />LOCK TABLES `articles` WRITE;<br />/*!40000 ALTER TABLE `articles` DISABLE KEYS */;<br />INSERT INTO `articles` (`id`, `title`, `content`)<br />VALUES<br /> (1,'我是标题','<h3>我是内容呀~~</h3><p>我真的是内容,不信算了,哼~ O(∩_∩)O</p>'),<br> (2,'我是标题','<h3>我是内容呀~~</h3><p>我真的是内容,不信算了,哼~ O(∩_∩)O</p>');<br>/*!40000 ALTER TABLE `articles` ENABLE KEYS */;<br>UNLOCK TABLES;
Then, refresh! You will see the following page:
Congratulations! Both M and C in MVC have been implemented! Next we start calling V (view).
Call View
Modify models/Article.php to:
<?php<br>/**<br>* Article Model<br>*/<br>class Article<br>{<br> public static function first()<br> {<br> $connection = mysql_connect("localhost","root","C4F075C4");<br> if (!$connection) {<br> die('Could not connect: ' . mysql_error());<br> }<br> mysql_set_charset("UTF8", $connection);<br> mysql_select_db("mffc", $connection);<br> $result = mysql_query("SELECT * FROM articles limit 0,1");<br> if ($row = mysql_fetch_array($result)) {<br> return $row;<br> }<br> mysql_close($connection);<br> }<br>}
Returns an array containing the query results. Modify HomeController:
<?php<br>/**<br>* \HomeController<br>*/<br>class HomeController extends BaseController<br>{<br> public function home()<br> {<br> $article = Article::first();<br> require dirname(__FILE__).'/../views/home.php';<br> }<br>}
Save and refresh, you will get the same page as above, the view is called successfully!
Almost everyone understands MVC by learning a certain framework. In this way, the framework may be used very familiarly. Once it is separated from the framework, it is impossible to write a simple page, let alone design the MVC architecture by oneself. In fact, here There aren’t that many ways, and the principles are very clear. Let me share my insights:
1. No matter how powerful the PHP framework is, it is still PHP and must follow the operating principles and basic philosophy of PHP. By grasping this, we can easily understand many things.
2. Logically speaking, a website made with PHP is no different from php test.php. It is just a string passed as a parameter to the PHP interpreter. It is nothing more than a complex website that calls the files and codes that need to be run based on the URL, and then returns the corresponding results.
3. Whether we see a "small framework" like CodeIgniter, which is composed of 180 files, or a "large framework" like Laravel, which has more than 3,700 files including vendors, they will be included in each URL. Under the driver, a executable string is assembled, passed to the PHP interpreter, and then the string returned from the PHP interpreter is passed to the visitor's browser.
4. MVC is a logical architecture. It is essentially designed to allow ultra-low RAM computers like the human brain to create large-scale software that far exceeds the RAM of human brains. In fact, the MVC architecture has been taking shape before the emergence of GUI software. The command Row output is also a view.
5. In MFFC, what a URL-driven framework does is basically as follows: the entry file requires the controller, the controller requires the model, the model interacts with the database to obtain data and returns it to the controller, and the controller then requires the view, The data is populated into the view, returned to the visitor, and the process ends.
If you are not too obsessed with your own control, it is recommended to use the ready-made mvc framework to greatly reduce the development time
MVC is not just about creating a few packages, but an idea. Of course, several packages will allow you to instantiate this idea - -, for example, if you have a table, and you instantiate this table, you must have a Class to include the fields, including some _get, _set methods, and then use another class to inherit this class and encapsulate some methods of adding, deleting, modifying, etc. This class can be understood as a Model layer and can be placed under a package. The logical page needs to require_noce this file class to instantiate this class, call the methods through the object, and then display it to the customer. The C layer and V layer in PHP do not need to be separated when no template is used (for example, smarty) So obviously, it is either PHP or Xiao Kuailing. It is not limited to the pure object-oriented approach of Java, but it does not lose the characteristics of data security and maintainability. This is the MVC of PHP~

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

I'm having a tough problem when developing a complex web application: how to effectively handle JavaScript errors and log them. I tried several methods, but none of them could meet my needs until I discovered the library dvasilenko/alterego_tools. I easily solved this problem through the installation of this library through Composer and greatly improved the maintainability and stability of the project. Composer can be learned through the following address: Learning address

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

I encountered a tricky problem when developing a new Laravel project: how to quickly build a fully functional and easy-to-manage content management system (CMS). I tried multiple solutions, but all gave up because of complex configuration and inconvenient maintenance. Until I discovered the LaravelCMS package mki-labs/espresso, which not only simple to install, but also provides powerful functions and intuitive management interface, which completely solved my problem.

I encountered a common but tricky problem when developing a large PHP project: how to effectively manage and inject dependencies. Initially, I tried using global variables and manual injection, but this not only increased the complexity of the code, it also easily led to errors. Finally, I successfully solved this problem by using the PSR-11 container interface and with the power of Composer.

When developing Yii framework projects, you often encounter situations where you need to obtain a large amount of data from the database. If appropriate measures are not taken, directly obtaining all data may cause memory overflow and affect program performance. Recently, when I was dealing with a project on a large e-commerce platform, I encountered this problem. After some research and trial, I finally solved the problem through the extension library of pavle/yii-batch-result.

During development, HTTP requests are often required, which may be to get data, send data, or interact with external APIs. However, when faced with complex network environments and changing request requirements, how to efficiently handle HTTP requests becomes a challenge. I have encountered a problem in a project: I need to send requests to different APIs frequently, and log the requests to facilitate subsequent debugging and analysis. After trying several methods, I discovered the yiche/http library. It not only simplifies the processing of HTTP requests, but also provides dynamic logging functions, greatly improving development efficiency.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.
