Using Composer to build your own PHP Framework (iii)--Design MVC

Source: Internet
Author: User
Tags autoload php framework

finally can "write once, publish everywhere", burst into tears!

This morning I started from a little more than four hours to 5:20, finally got a emlog MarkDown plugin! Welcome Emloger Try!

For this tutorial sample code see Https://github.com/johnlui/My-First-Framework-based-on-Composer

Review

In the previous tutorial, we built two simple routes using the CODINGBEAN/MACAW Composer package, the first one responding to GET '/fuck ', and the other holding all requests. In fact, for the PHP framework, there is a route to have everything. So the next thing we need to do is make the MFFC framework more standardized and more plump.

This involves the additional value of the PHP framework: establishing development specifications to facilitate multi-person collaboration, using tools such as ORM and template engines to improve development efficiency.

Formally start planning folders

New Mffc/app folder, create controllers, models, views three folders in the app, begin to formally embark on the journey of MVC.

(who said I copied Laravel, I copied the Rails:-D)

Using namespaces

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 "

Add a route: Macaw::get (', ' [email protected] '), open the browser to access http://127.0.0.1:81/directly, the following prompt appears:

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 the HomeController class? Because we didn't let him load it automatically, modify the Composer.json to:

{"  require": {    "Codingbean/macaw": "Dev-master"  },  "AutoLoad": {    "Classmap": [      "app/ Controllers ",      " App/models "    ]  }}

Run composer Dump-autoload, wait a moment, refresh, and you will see the following (Don't forget to adjust the encoding Oh ~):

Congratulations, the use of namespaces is successful!

Connecting to a database

Create a new models/article.php file with the contents (database password please change it 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 ' 

To modify the controllers/homecontroller.php file:

<?php/*** \homecontroller*/class HomeController extends basecontroller{public    function Home ()  {    Article::first ();  }}

Refresh, this time will get the article class not found information, because we did not update the automatic loading configuration:

Composer Dump-autoload

In the waiting time, we go to set up the database MFFC, build the table articles inside, design two fields title, content is used to record information, and fill in at least one piece of data. You can also run the following SQL statement after establishing the MFFC database:

DROP TABLE IF EXISTS ' articles '; CREATE TABLE ' articles ' (  ' id ' int (one) 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 ', ' Conte NT ') VALUES (1, ' I am the title ', ' 

Then, refresh! You will see the following pages:

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

Call View

Modify the 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 that contains the results of the query. 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, the view call succeeds!

Almost everyone through learning a framework to understand the MVC, so that the framework may be used very well, once away from the framework of a simple page can not be written, let alone design MVC architecture, in fact, there is not so many doorways, the principle is very clear, I say my sentiment:

1. PHP Framework is no more awesome, he is also PHP, but also to follow the principles of PHP operation and basic philosophy. Seize this and we can easily understand a lot of things.

2. PHP makes a Web site logically, and PHP test.php no difference, just a string as a parameter passed to the PHP interpreter. It's just that complex Web sites invoke the files and code that need to be run based on the URL, and then return the corresponding results.

3. Whether we see a "small frame" consisting of 180 files such as CodeIgniter, or a "big frame" in which Laravel vendor a total of more than 3,700 files, they will assemble a string that can be run at each URL, passed to the PH The P interpreter, and then passes the string returned from the PHP interpreter to the visitor's browser.

4. MVC is a logical architecture, in essence, to allow ultra-low-RAM computers such as the human brain to produce large-scale software that is far beyond the human brain's RAM, in fact, the MVC architecture has taken shape before GUI software appears, and command-line output is a view.

5. In MFFC, a URL-driven framework does something like this: The ingress file require controller, the controller require model, the model and the database interact to get the data back to the controller, the controller again require the view, the data is populated into the view, returned to the visitor, and the process ends.

Https://lvwenhan.com/php/408.html

Using Composer to build your own PHP Framework (iii)--Design MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.