Home >Backend Development >PHP Tutorial >Learn to implement mvc simple framework with php
The above file just creates an object named DemoController and contains an index method, which outputs hello world. Next, execute the index method in DemoController in index.php. File: index.php
Run index.php, you can see the output hello world. The essence of mvc is to run the controller we want to run through the only entrance. Of course, the controller part should be determined by the uri, so let's rewrite index.php so that it can determine which controller to run through the uri. Modify index.php code:
Enter http://localhost/index in the browser. php?c=demo&a=index, we got our hello world. Of course, if we have another controller and want to run it, we only need to modify the values of c and a in the url parameters. Related instructions: 1. PHP is a dynamic language. We can directly get the object we want and run the method we want through the string new, that is, the new $c_name above, we can understand it as new 'DemoController', because the value of $c_name itself It's 'DemoController'. Of course, writing new 'DemoController' directly like this won't work. The 'DemoController' string must be transferred through a variable. The method is the same. 2. The value of c in our URL is demo, which means the value of $c_name should be demoController. Isn’t PHP case-sensitive? Can it run like this? The sentence "php is case-sensitive" is incomplete. In php, only variables (preceded by $) and constants (defined by define) are case-sensitive, while class names, method names and even some keywords are not case-sensitive. written. And true, false, null, etc. can only be all uppercase or all lowercase. Of course we'd better be case-sensitive during the actual encoding process. 3. View We only output a "hello world" in the previous controller, which did not achieve the effect of mvc. Next, I will add the view function on this basis. I believe that by now everyone can basically think of how to add the view function. Yes, it is achieved through the evil require or include. First, we create an index.php under the view folder and write anything (haha, I still wrote hello world). Then rewrite the previous DemoController.
and run it in the browser to see if the content we want has been output. Then we pass some data to the view through the controller to see:
view index.php file in the folder
|