


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:
/**<br>* BaseController<br>*/<br>class BaseController<br>{<br> <br> public function __construct()<br> {<br> }<br>}<br>
New controllers/HomeController.php file:
<pre data-lang="php"> /**<br>* \HomeController<br>*/<br>class HomeController extends BaseController<br>{<br> <br> public function home()<br> {<br> echo "<h1 id="控制器成功">控制器成功!</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):
/**<br>* Article Model<br>*/<br>class Article<br>{<br> public static function first()<br> {<br> $connection = mysql_connect("localhost","root","password");<br> if (!$connection) {<br> die('Could not connect: ' . mysql_error());<br> }
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 id="row-title">'.$row["title"].'</h1>';<br> echo '<p>'.$row["content"].'</p>';<br> }
mysql_close($connection);<br> }<br>}
Modify controllers/HomeController.php file:
<p>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: </p> <pre data-lang="html"> 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 id="我是内容呀">我是内容呀~~</h3><p>我真的是内容,不信算了,哼~ O(∩_∩)O</p>'),<br> (2,'我是标题','<h3 id="我是内容呀">我是内容呀~~</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:
/**<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:
/**<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~

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.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools