Design mvc,composermvc_php tutorial for building your own PHP framework with composer

Source: Internet
Author: User
Tags autoload php framework

Use composer to build your own PHP framework design MVC,COMPOSERMVC


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 ', ' template engine ' 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 "

Controller success!

";
}
}

Add a route: Macaw::get (', ' homecontroller@home '); ', open the browser to access http://127.0.0.1:81/directly, and 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 '

'. $row ["title"]. '

';
Echo '

'. $row ["Content"]. '

';
}
    Mysql_close ($connection);
}
}

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 build database MFFC ', build table articles in it, 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 ', ' content ')
VALUES
(1, ' I am the title ', '

I am the content Ah ~ ~

I really am content, don't believe forget, Hum ~ O (∩_∩) o

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

I am the content Ah ~ ~

I really am content, don't believe forget, Hum ~ O (∩_∩) o

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

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 the "big frame" of Laravel "plus vendor altogether more than 3,700 files," they will assemble a string of strings that can be run at each URL, passing it to PHP interpreter, and then pass 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.


Build the MVC framework in PHP language

If you're not too pursuing your own control, it's recommended to use an out-of-the-box MVC framework to scale down development time

PHP MVC Framework

MVC is not a set of packages, but a thought, of course, a few packages will let you take the idea of the example----you have a table, for example, you have a class to include the fields, including some _get,_set methods, and then inherit this class with another class, Encapsulation of some additions and deletions and so on, this class can be understood into the model layer, can be placed under a package, and the logical page looking to require_noce this class to instantiate this type, through the object to invoke the method, and then display to the client, the C layer and V layer in PHP in the case of no template ( For example Smarty is not separated so obvious, or how is PHP that ~ small fast spirit-the whole is not confined to Java that pure object-oriented, but without losing to the data security and maintenance features, this is the PHP mvc~

http://www.bkjia.com/PHPjc/903481.html www.bkjia.com true http://www.bkjia.com/PHPjc/903481.html techarticle Build Your own PHP framework with Composer MVC,COMPOSERMVC review in the previous tutorial, we used CODINGBEAN/MACAW this Composer package to build two simple routes, the first ...

  • 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.