CodeIgniter MVC model
Sep 3, 2020
PHP
CodeIgniter
I mainly write how to write the MVC model of CodeIgniter.
#Controller
-
-Create a controller that implements a class for creating static pages.
The class to be created inherits the CI_Controller class of system / core / Controller.php.
Take the name of the page as an argument.
The method to load that page is show ()
class Pages extends CI_Controller { public function show ($ page ='home') { } }
-
-Class inheritance –Override: If the same method is used in the small class and the parent class, Coctus takes precedence and overwrites the parent class.
-
-Method
Methods with special roles
–Default method: index () –Method executed when the second method is empty –Remap method: _remap () –Called prior to the default method (no need for the default method) –Normal URI routing is ignored. –Output method: _output () –You can do some processing before returning the data to the user’s browser. –Constructor method: Same name as class name () –Executed only once when the controller class is called. –Convenient when you want to initialize a library that is commonly used in the controller or when you want to execute a fixed process every time.
```php function __construct () { // Call the constructor of the parent controller class parent :: __ construct (); } `````
–Private method: _Arbitrary method name () –Cannot access directly from the URL. –Called via the default method in the following format.
```php function index () { echo $ this-> _private_method (); } function _private_method () { echo'This is a private method'; } `````
#View
-
Feature –Can be written in PHP syntax and HTML tags –Views can be linked and have a hierarchical structure. –Helpers and libraries are available directly. –There is a cache function. –You can create pseudo variables like Smarty.
-
-Load View
$ this-> load-> view ('filename', associative array of data or object)
<? php class Hello extends CI_Controller { // Contents of index () method >>'Hello World' public function index () { echo "Hello World"; } // Contents of about () method >> about.php public function about () { $ this-> load-> view ('about'); } . } ?>
-
loop –Iterate using the foreach syntax.
// Controller function index () { $ data ["title"] = "Sample" $ data ["contents"] = array ("apple", "orange") $ this-> load-> view ("filename", $ data); }
<title> <? = $ title?> </ Title> .. .. .. <ul> <? php foreach ($ contents as $ item) :?> <li> <? = $ Item;?> </ Li> <? php endforeach;?> </ ul>
#Model
-
-How to write Model
<? php class Model_name extends CI_Model { public function __construct () { parent :: __ construct (); } } ?>
-
-Load Model –Read
// When you want to read /system/application/models/read/read.php $ this-> load-> model ('read / read');
–Method execution
$ this-> read-> function ();