Using Composer to build your own PHP Framework Design MVC_php instance

Source: Internet
Author: User
Tags autoload php website
Almost everyone knows about MVC by learning a framework. This may be very familiar with the framework. Once a simple page of the framework cannot be written, let alone designing the MVC Architecture, in fact, there are not so many channels here, And the principle is very clear. Review

In the previous tutorial, we used the codingbean/macaw Composer package to construct two simple routes. The first one is to respond to GET '/fuck', and the other will hold all requests. In fact, for the PHP framework, everything is possible with routing. So what we need to do next is to make the MFFC framework more standardized and plump.

This involves another value of the PHP framework: the establishment of development specifications to facilitate 'multi-person collaboration ', the use of ORM, 'template engine and other tools to 'improve development efficiency '.

Officially start planning folders

Create MFFC/app folders, create three folders: controllers, models, and views in the app, and start the MVC journey.

(Who said I copied Laravel? I copied Rails:-D)

Use namespace

Create the controllers/BaseController. php file:

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

public function __construct()
{
}
}

Create the controllers/HomeController. php file:

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

Public function home ()
{
Echo "Controller successful! ";
}
}

Add a route entry: Macaw: get ('', 'homecontroller @ home'); 'and open a browser to access http: // 127.0.0.1: 81/'. The following prompt is displayed:

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

Why can't the HomeController class be found? Because we didn't let him load it automatically, modify composer. json:

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

Run composer dump-autoload. Wait a moment and refresh. You will see the following content (don't forget to adjust the encoding ~) :


Congratulations! namespace used successfully!

Connect to database

Create a new models/Article. php file with the following content ):

<?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 ''.$row["title"].'';
echo '

'.$row["content"].'

';
}
    mysql_close($connection);
}
}

Modify the controllers/HomeController. php file:

<?php/*** \HomeController*/class HomeController extends BaseController{  public function home() {  Article::first(); }}

Refresh. At this time, we will get information not found in the Article class, because we did not update the automatic loading Configuration:

composer dump-autoload

During the waiting time, we will create the database mffc' and create the table articles in it. We will 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 the mffc database is created:

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 'Article' WRITE;
/*! 40000 alter table 'articles' disable keys */;
Insert into 'articles' ('id', 'title', 'content ')
VALUES
(1) 'I am the title' and' I am the content ~~

I am really a content. Forget it, hum ~ O (partition _ partition) O

'),
(2) 'I am the title' and' I am the content ~~

I am really a content. Forget it, hum ~ O (partition _ partition) O

');
/*! 40000 alter table 'Article' enable keys */;
Unlock tables;

Then, Refresh! You will see the following page:


Congratulations! Both M and C in MVC have been implemented! Next we will call V (view ).

Call View

Modify models/Article. php:

<?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 and refresh. You will get the same page as above. View call successful!

Almost everyone knows about MVC by learning a framework. This may be very familiar with the framework. Once a simple page of the framework cannot be written, let alone designing the MVC Architecture, in fact, there are not so many doorways here, And the principle is very clear. Let me talk about my feelings:

1. the PHP framework is awesome. It is also PHP, and it should follow the operating principles and basic philosophy of PHP. By grasping this point, we can easily understand many things.

2. the PHP website is logically similar to php test. php, and only a string is passed as a parameter to the PHP interpreter. A complex website calls the files and code to be run based on the URL and returns the corresponding results.

3. no matter whether we see a "small frame" composed of 180 files such as CodeIgniter, or a "large frame" composed of a "large frame" like Laravel "and a total of more than 3700 files in vendor ", they will assemble a string that can run under each URL driver, pass it to the PHP interpreter, and then send the string returned from the PHP interpreter 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 software that far exceeds the RAM of the human brain. In fact, the MVC Architecture has taken shape before the appearance of GUI software, command Line output is also a view.

5. in MFFC, a URL-driven framework basically does the following: the entry file require controller, the Controller require model, and the model and the database interact to obtain data and return it to the Controller. Then, the Controller returns the require view, enter the data in the view and return it to the visitor. The process is complete.

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.