Developed from the PHPMVC framework (1)

Source: Internet
Author: User
Develop your own PHPMVC framework (I). This tutorial is translated from BuildaPHPMVCFrameworkinanHour of JohnSquibb, but it has been changed. Original article: johnsquibb. the comtutorials tutorial allows you to master the basic concepts of using mvc to develop php applications. This tutorial is divided into three parts. now this is the first part. There are many popular frameworks on the market for developing your own php mvc framework (1)

Build a php mvc Framework in an Hour from John Squibb, but it has been changed.

This tutorial allows you to master the basic concepts of developing php applications in the mvc mode. This tutorial is divided into three parts. now this is the first part.

There are many popular frameworks on the market for you to use, but we can also develop an mvc framework by ourselves. Using the mvc model can greatly reduce the time for application development, in addition, it can better organize the project source code, and some modules can also be used in other projects. Now I want to teach you how to write a simple mvc framework. This project is simple and lightweight, so it may not be the best practice or secure, and needs to be improved in practical applications.

Technology used: php, object-oriented development method.

Start

First, create three folders under the root directory of the website

  • Models
  • Views
  • Controllers

Create a new file in the root directory:

  • Index. php

Now the project structure should be like this

§ Website root directory

§ Index. php

§ Models/

§ Views/

§ Controllers/


Index. php is the entry point of the entire web application. all user requests will pass through it. We will write some code to distribute user requests to the corresponding controllers, which are stored in the controllers folder. Then, we can use the following method to achieve page jump:

  • Http: // your domain name. com/index. php? Page1
  • Http: // your domain name. com/index. php? Page2
  • Http: // your domain name. com/index. php? Page3
Set the front-end controller index. php

First, define the website root directory and website domain name in index. php for access throughout the application.

 

After the root directory of the website is defined, php files in other directories can be easily referenced in any php file, because index. php is an entry file, so that the variables defined in it can be accessed throughout the application.

Set router. php (forward user requests to the corresponding controller)

Create a new file named "router. php" in the controllers directory to process all page requests. Imagine the router in your home. it routes the internet to every computer in your home. The router. php file will obtain the page request passed into index. php, and then assign the request to different controllers (controllers ).

Code in route. php:

  
This code will get the request parameters passed in to the application. QUERY_STRING is "? "All strings.

  • Http: // your domain name. com/index. php? Page1

The above address will get "page1 & action = login" in the code. to separate page1 from the following parameters, we need to add the following code in route. php:

// Parse the $ request variable to obtain the page requested by the user (page1) and other GET variables (& separated variables), such as a request http: // your domain name. com/index. php? Page1 & article = buildawebsite is parsed as array ("page1", "article = buildawebsite") $ parsed = explode ('&', $ request ); // the page requested by the user, as shown in page1 above, is the first variable of $ parsed. after shift, the array is array ("article = buildawebsite") $ page = array_shift ($ parsed ); // The rest are GET variables and parse them out $ getVars = array (); foreach ($ parsed as $ argument) {// use "=" to separate strings, variable on the left and value list ($ variable, $ value) = split ('=', $ argument) on the right; $ getVars [$ variable] = $ value ;} // This is a test statement. print "The page your requested is '$ page'"; print' will be deleted later'
'; $ Vars = print_r ($ getVars, TRUE); print "The following GET vars were passed to the page:
".$vars."
";

Now we need to introduce route. php in index. php.

   
If the problem persists, open your browser and enter:


  • Http: // your domain name. com/index. php? News & article = howtobuildaframework

The following output is displayed:

The page you requested is 'news'The following GET vars were passed to the page:Array([article] => howtobuildaframework)

If the preceding output is not displayed, check whether your server configuration is correct and whether the code is correct.

Now let's add a page to our website, so that router. php can generate a page instead of directly outputting the above information.


Create a controller)

Create a new file named "news. php" in the controllers folder and define the following class:

   '; $ Vars = print_r ($ getVars, TRUE); print ("The following GET vars were passed to this controller :"."
".$vars."
");}}

Note that we copied the test code in route. php and made some modifications. We put it in the main function. Now let's modify the code in route. php:

   _ Controller"News_Controller) $ class = ucfirst ($ page ). '_ controller'; // initialize the corresponding class if (class_exists ($ class) {$ Controller = new $ class;} is the else {// class named correctly? Die ('class does not exist! ') ;}} Else {// The File die ('page does not exist! ');} // Once the controller is initialized, its default function main () is called (); // pass the get variable to $ controller-> main ($ getVars);?>

Access http: // your domain name again. com/index. php? News & article = howtobuildaframework, you will see the information printed from News_Controller. Note: We are now using die () to handle errors. we can use other better error handling methods to regulate it, but it is enough to use die () now. try accessing other pages such as http: // your domain name. com/index. php? Books, you will see "page does not exist! "Error. Create a Model to improve News_Controller. Suppose we have some news clips for readers to read, so we need the News_Controller controller to call a model to capture relevant news clips, whether they are stored in a database or a file. Create a file "news. php" in the models folder. the code is as follows:

   

Now, we need to make some changes to the news controller to open the news in controllers. php: change the code of the main function of the News_Controller class to the following. in this way, we will see the information printed on the screen during the initialization of "News_Model:

public function main(array $getVars){    $newsModel = new News_Model;}
Refresh the page and you will see:

Fatal error: Class 'News_Model' not found in /var/www/mvc/controllers/news.php on line xx
Wait, this is not the result we want! We are trying to load a non-existent class. The reason is that the/models/news. php file is not introduced. To solve this problem, let's take a look at router. php and add some code at the top of it:

// When the class is initialized, the related file function _ autoload ($ className) {// Parse the file name to obtain the file storage path, for example, News_Model indicates the news in the models folder. php (here is the author's naming convention) list ($ filename, $ suffix) = split ('_', $ className); // form the file path $ file = SERVER_ROOT. '/models /'. strtolower ($ filename ). '. php '; // Obtain the file if (file_exists ($ file) {// introduce the file include_once ($ file );} else {// The File does not have a die ("File '$ filename 'ining ining class' $ classname' not found. ");}}
This function reloads the built-in PHP autoload function. When we try to initialize a non-existent class, this 'magic method' allows us to intercept the action executed by php. By using the _ autoload function, we can tell php to find the location of the file containing this class. Assuming that you have followed the naming conventions for classes and file names in this article, you do not have to manually introduce files containing these classes whenever you initialize a class!

Save route. php and refresh the browser again. you will see:

I am the news model

Let's define some functions in the news model class to provide articles. Now, we only define an array, save some articles, and provide a function for the controller to obtain an article based on the title. Modify models/news. php:


    Array ('title' => 'New website', 'content' => 'Welcome to the site! We are gglad to have you here. '), // 2 'mvc' => array ('title' => 'php mvc Frameworks are Awesome! ', 'Content' =>' It really is very easy. Take it from us! '), // 3 'test' => array ('title' => 'testing', 'content' => 'This is just a measly test article. '); public function _ construct () {}/*** get an article by title ** @ param string $ articleName ** @ return array $ article */public function get_article ($ articleName) {// Get an article from the array $ article = $ this-> articles [$ articleName]; return $ article ;}}?>

Modify the main function in controllers/news. php:

Public function main (array $ getVars) {$ newsModel = new News_Model; // Get an article $ article = $ newsModel-> get_article ('test '); print_r ($ article );}
Currently, we have not considered filtering user input, because we are only trying to get everyone to know the basic content of php mvc as soon as possible, so we don't have to worry too much about it now.

If you visit the following URL:

§Http://yourdomain.com/mvc/index.php? News & article = test

You will see the following output:

Array ( [title] => Testing [content] => This is just a measly test article. ) 

Create a VIEW)

Now we have a controller and a model, with only one view. A view is a presentation layer that is the most frequently accessed part of your application. As I mentioned before, a view provides user interfaces separated from the business logic. There are many ways to do this. You can use the template engine Smarty or something similar. You can also write your own template engine, but it must be a very difficult task. Finally, you can use the native php view.

For the moment, the php view is sufficient. This is just like the previous mixed programming of php and html code, but the difference is that our business logic has been separated from the view. Take a look at the following code:

                Welcome to Our Website!        
            News        
            

Note that embedded php labels use PHP shortcuts. In this way, we can directly output our content to HTML. Create a file "news. php" in the views folder and copy the above code. Now we have a view file, but we need a method to interact with the view. Create a file "view. php" in the models folder and add the following code:


    Render = $ file ;}}/*** accepts the variables assigned by the controller, and save it in the data array ** @ param $ variable * @ param $ value */public function assign ($ variable, $ value) {$ this-> data [$ variable] = $ value;} public function _ destruct () {// changes the data array in the class to a local variable of the function, to facilitate the use of $ data = $ this-> data; // rendering view include ($ this-> render);} in the view template );}}

Now, the last thing to do is to load the view from News_Controller. Modify controllers/news. php:

    Get_article ($ getVars ['article']); // create a view and input the template variable $ view = new View_Model ($ this-> template) of the controller ); // assign the document data to the view template $ view-> assign ('title', $ article ['title']); $ view-> assign ('content ', $ article ['content']) ;}}?>


After loading the page, you can see that the variables in your view template have been correctly replaced. Well, your simple MVC framework has been set up. next I will continue to talk about developing my own PHP MVC framework (II).

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.