Finally, we can “write once, publish everywhere” with tears on our faces!
This morning, I started working from 1:00 to 5:20, and finally got an Emlog MarkDown plug-in! Welcome Emloger to try!


The original article was published on my personal website: using Composer to build your own PHP framework step by step (3) – Design MVC


See https://github.com/johnlui/My-First-Framework-based-on-Composer for sample code for this tutorial


review

In the last tutorial, we usedcodingbean/macawThis Composer package builds two simple routes, the first is response.GET ‘/fuck’The other holds all requests. In fact, for the PHP framework, with routing there is everything. So the next thing we need to do is to make the MFFC framework more standardized and fuller.

This involves another value of the PHP framework: establishing development specifications to facilitateMultiplayer collaborationUseORMtemplate engineTools such asImproving Development Efficiency


Begin formally

Planning Folder

Newly buildMFFC/appFolder, created in appcontrollersmodelsviewsThree folders, began to officially embark on the MVC journey.
(Who said I copied Laravel? I copied Rails: -D.)

using namespace std

New controllers/BaseController.php file:

<?php
/**
* BaseController
*/
class BaseController
{

  public function __construct()
  {
  }
}

New controllers/HomeController.php file:

<?php

/**
* \HomeController
*/
class HomeController extends BaseController
{

  public function home()
  {
    echo "

<h1> The controller succeeded! </h1>

";
  }
}

Add a route:Macaw::get('', '[email protected]');Open the browser for direct accesshttp://127.0.0.1:81/The following prompts appear:

Fatal error: Class 'HomeController' not found in /Library/WebServer/Documents/wwwroot/MFFC/vendor/codingbean/macaw/Macaw.php on line 93

Why didn’t you find it?HomeControllerClass? Because we didn’t let him load it automatically, we changed composer.json to:

{
  "require": {
    "codingbean/macaw": "dev-master"
  },
  "autoload": {
    "classmap": [
      "app/controllers",
      "app/models"
    ]
  }
}

Functioncomposer dump-autoloadWait a minute, refresh, and you’ll see the following (don’t forget to adjust the code):

Construct your own PHP framework step by step with Composer (3) - Design MVC

Congratulations on the successful use of namespaces!

Connect to the database

New model/Article.php file, content is (database password, please change 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)) {
      echo '<h1>'.$row["title"].'</h1>';
      echo '<p>'.$row["content"].'</p>';
    }

    mysql_close($connection);
  }
}

Modify the controllers/HomeController.php file:

<?php

/**
* \HomeController
*/
class HomeController extends BaseController
{

  public function home()
  {
    Article::first();
  }
}

Refresh, and you’ll get it.ArticleClass did not find information because we did not update the automatic loading configuration:

composer dump-autoload

During the waiting time, we went to build the database.mffcCreate tables in itarticlesDesign two fieldstitlecontentUsed to record information and fill in at least one piece of data. You can also build it.mffcThe database will run the following SQL statements later:

DROP TABLE IF EXISTS `articles`;

CREATE TABLE `articles` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) DEFAULT NULL,
  `content` longtext,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

LOCK TABLES `articles` WRITE;
/*!40000 ALTER TABLE `articles` DISABLE KEYS */;

INSERT INTO `articles` (`id`, `title`, `content`)
VALUES
    (1,'I'm the title', '

<h3> I am the content.~~</h3>



<p> I'm really content, don't believe it, hum O</p>

'),
    (2,'I'm the title','

<h3> I am the content.~~</h3>



<p> I'm really content, don't believe it, hum O</p>

');

/*!40000 ALTER TABLE `articles` ENABLE KEYS */;
UNLOCK TABLES;

Then, refresh! You will see the following pages:

Construct your own PHP framework step by step with Composer (3) - Design MVC

Congratulations! M and C in MVC have been implemented! Next we start calling V (view).


Call view

Modify models/Article.php to:

<?php
/**
* Article Model
*/
class Article
{
  public static function first()
  {
    $connection = mysql_connect("localhost","root","C4F075C4");
    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)) {
      return $row;
    }

    mysql_close($connection);
  }
}

Returns an array containing the query results. Modify HomeController:

<?php
/**
* \HomeController
*/
class HomeController extends BaseController
{

  public function home()
  {
    $article = Article::first();
    require dirname(__FILE__).'/../views/home.php';
  }
}

Save, refresh, you will get the same page as above, view call success!


Almost everyone knows MVC by learning a framework, which may be very familiar with the framework. Once you leave the framework, you can’t write a simple page, let alone design your own MVC architecture. In fact, there are not so many doors in it. The principle is very clear. I will tell you my feelings:

  1. The PHP framework is also PHP. It should follow the operation principle and basic philosophy of PHP. We can easily understand many things by grasping this point.
  2. PHP’s website logically followsphp test.phpThere’s no difference. It’s just a string passed to the PHP interpreter as a parameter. It’s just that complex websites call the files and codes that need to be run according to the URL, and then return the corresponding results.
  3. Whatever we see isCodeIgnitersuch180 documentsThe “small framework” of composition, orLaravelsuchTogether with vendor, there are more than 3700 files in total.Driven by each URL, they assemble a running string, pass it to the PHP interpreter, and then pass the string returned from the PHP interpreter to the visitor’s browser.
  4. MVC is a kind of logical architecture, essentially to enable computers with ultra-low RAM, such as the brain, to produce large-scale software that is far superior to human brain RAM. In fact, MVC architecture was formed before GUI software came into being, and command line output is also a view.
  5. In MFFC, a URL driver framework basically does the following things: the entry file require controller, the controller require model, the model and database interaction to get data back to the controller, the controller require view, fill the data into the view, return to the visitor, and the process ends.

Next step: Construct your own PHP framework step by step using Composer (4) – Using ORM