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~