Simple ways to use CI framework
Release: 2016-07-28 08:28:57
Original
1475 people have browsed it
-
CodeIgniterFramework
-
1, MemoriesMVC
-
1.1 , M: model, provide data, save data
-
1.2, V: View, only responsible for displaying the form form
-
1.3, C: Controller, coordinating the model and view
- 1.4 , action: Action is a method in the controller, used to be requested by the browser
-
-
2, CI in MVC
-
CI Introduction: CodeIgniter is a lightweight but powerful php framework, based on the MVC design pattern.Provides a rich set of class libraries
-
2.1, accessed url used pathinfo
-
2.2, format: entry file/controller/action ( Default pathinfo format)
-
2.3, application Directory:
-
ControllersControllers
-
ModelsModels
-
Views View
-
2.4, the default controller is welcome
-
2.5, the default action is index
-
2.6, file names must be all lowercase
-
-
3, controller (controller):
-
3.1, no need to add suffix, just the class name .php
- 3.2、 File names are all lowercase, such as user.php (uppercase file names are not supported by browsers)
-
3.3, all controllers, directly or indirectly inherited from CI_Controller Classes, the first letter of the class name is capitalized
-
3.4, method names are not case-sensitive
-
Action requirements:1.must start with public
-
-
2. cannot start with an underscore (_)
-
Attention!If the method name is the same as the class name, it will be regarded as a constructor method (__construct)
- 4
, view (-
view)
- 4.1
, load the view in the controller: -
$this->load->view("user_add"); //No Add extension 4.2
, load the view in the controller: -
$this->load->view("user/ add”);//Without extension Note: You can call
$this-
->load->view(view); 4.3
, in the view, directly use the native -
php code4.4
, assign variables in the controller: -
$this->load - >vars("variable name in view", variable name in php); abcdefg ";
- $this->
- load->vars("str",$str
- ); Use in view :php echo $str;?> 4.5, assign multiple variables in the controller:
-
For example: $str
- ="
- abcd";
- $list =
- array("id"=>" 1"," name
- ”=>”zhangsan”,”pwd”=>”1234”);$data [“str "]= $str;$data
- ["list"]= $list; $this
- -> ;load->vars($data); The framework will solve it by itself
php-
Short tags =…?>4.7, recommended use: phpforeach
(- $list
as- $key => Attributes5.1、$this
->-
loadAttributes5.1. 1, instance of loader class system /core/Loader.
php-
-
5.1.
2- 、
CI_-
Lo Method provided by ader: $this ->load
->-
view()load view$this->load-> vars() Assign variables to the view
-
$this->load-> ;database()Load database operation object
-
$this -> load-> )Help objects $this
-> -
5.2, $this->uriattributes
-
5.2.1, instance of loader class system/core/URI.php
- 5.2.2 Methods provided by , CI_URI:
-
$this->uri->Segment(n) is used to get URL The n parameter in represents the controller
1-
, the action represents 2, and the value 1 represents 3 , value 2 is represented by 4…Usage
1-
: Entry file/controller/action/value1/value2echo $this
- >-
uri->segment(3);//Output value 1Usage
2-
: index.php /Controller/Action/6//can be obtained directly; the parameters must correspond correctly
- public
function-
($id=0) {echo $id
;-
//output 6}
-
-
5.3、$this->inputattribute
-
5.3. 1, instance of loader class system Methods provided by /core/Input.php
-
5.3.2, CI_Input:
-
-
$this ->input->post('username'); //$_POST["username"]; -> ;
- input->server("DOCUMENT_ROOT");//$_SERVER["DOCUMENT_ROOT"]$this-&g t;
- input -> server ("SERVER_ADDR");//Server-side IPNote: In the view, you can directly use $this
- to access the properties in the super object 6, access database 6.1
- , modify configuration file: application/config
- /database
- .php
- 6.2 , Load database operation class:
- $this->load->database();After successful loading, it will be placed in the properties of the super object, by default The attribute name is db
- $this->db6.3, $query= $this
- -& gt;db- >
- query($sql);
- //The return value is the object (array_fetch_object)$sql = $this-> db ->last_query($sql);//Display the last executed sql statement
- 6.3.1,$ query= $this-> $list= $query->
$list -
= $query-> = $query->row();//Return the first piece of data, which is directly an object6.7,$row=
- $query ->row_array();//Return the first data, which is an array6.8, $count=
- $query-> num_rows();//Return the number of rows in the result set6.9, $field=
- $query->num_fields (); //Return the requested number of fields6.10, $count=
- $query->affected_rows();//Return the number of affected rows 6.11、$id=
- $query->insert_id();//Return self-increasing ID 7 , configuration in the database
-
7.1, automatic loading db: in application/config
- /autoload .php中Configuration:
-
$autoload["libraries"]= array("database");
-
This way you don't need $this -> load->database();
-
-
7.2, parameter binding
-
$name = $this ->input -> ->post ("pwd");
-
//Use question marks to bind parameters $data[0]= $name ;
- $data[
- 1]= $pwd;//Use a two-dimensional array to pass values $sql
- =" insertinto ci_user(name,pwd
- ) values (?,?)”;//Multiple question marks, you need to pass an index array$bo ol = $this-> The value is boolean 7.3, table prefix configuration is configured in application
- /config/database.php: $db[' default']['dbprefix']
- ='ci_
- ';$db['default '][' swap_pre']='
- ci_';'; The configuration is the same. In the code, just write the name after the table prefix directly. If the project table prefix changes in the future, you only need to modify it. $db['default']['dbprefix']=
- 'new_', in the code ci_ will be automatically replaced by new_ 8, database operation (
- AR model) 8.1, configuration application/ cinfog/database. php中$active_record
- = TRUE
- ;8.2, in the configuration file, after configuring the table prefix,
will be added automatically - 8.3、 Find (get): $res = $this->db->
- get('table name'); / /Return the result set object $list
- = $res->
- result();//Return the array, the array is one object $ list
- = $res-> ) ://Data uses associative array$data["database field name"]=
- value;//$this->input->post("name ");$data["database field name"]=value;
- $res = $this->db -> ;insert("data table name",
- $data);//return result boolean;8.5
- , modify (update
- ): //Data uses associative array$data["database field name"]
- =value;//$this->input->post("name"); $data
- ["database field name"]=value; $where = array("id" =>" 4 ”);
-
-
$res = $this->db->update("data table name",$data,$where ) ;//return result boolean;
-
8.6、delete(delete):
-
$where = array("id ”=> ;"4");
-
$res = $this->db->dalete("data table name", $where);//Return result boolean;
-
-
9, AR coherent operation
- 9.1、$res = $this-> -> from("user")//Data table name->
- where("id
>",3)//Conditions
There must be a space between id and >
-
->order_by("id
desc")//Sort ->
- limit(3,1)//Paging; means skip 1 item, take 3 items , opposite to tp
-
->get();//Get data$list = $res
- ->result _array() ;9.2
- , where() conditionsConditional symbols: ">", ">=", "<", "<=", "=", "!="; If you don't specify a condition, the default value is "=" $this->db
- ->where("field","value")->get();
-
For example:
- $res = $this
- ->db->where("name","admin")-> get ();//"="9.2.
- 2、$res= $this->db - >where("field=","value")->get();For example: $res=
- $this- >db-> When there are spaces 2 or multiple conditions: use array()9.2.3, $res=
- $this -> get();For example: $res= $this->db->where( array( "name
- " =>"admin","id
- >3" =>"2"))-&g t; get();9.2.4, complex query statements use $this->db-> query(
- $sql,$data);//Use question marks to bind parameters9.3、joinConnection query
-
9.3.1, the default is left query (left
join … on)
-
$this->db->select("field")
-
- >from ("data table name")
-
->join('join table','join condition')
-
-> get (); //The default is left query (left
join … on) For example:
-
$this->db->select(“*”)
-
-> from ("user")
-
->join('category', user.id= category. id)//The default is left query (left
join )
- ->get();
- 9.3.2. Select the connection through the third optional parameter of join(). The optional parameters include: left, right, outer, inner, left outer, right outer
- For example:
- $this->db->select(“*”)
- ->from(“user”)
- ->join ("category", "user.id = category.id", "left")//Specify through the third parameter
- ->get();
- 10. Extended CI controller
-
- 10.1. Extending the controller
- 1. Create a new controller (MY_Controller) in application/core. The new controller inherits the CI_Controller class and can be extended from the controller you created.
- For example: class MY_Controller extends CI_Controller{
- Public function __consreuct(){
- Parent::__construct(); //Call the constructor of the parent class
-
//Login verification
- //Permission verification
- }
- }
- 2. Let welcome.php inherit the controller you created (MY_Controller) and indirectly inherit CI_Controller.
- 3. The controller prefix can be modified
- in application/config/config.php:
-
$config['subclass_prefix'] = 'MY_';
- 11. Model
- 11.1. Model file naming: user_model.php, category_model.php, file name in lowercase
- Recommendation: use _model as the suffix for the model file name to prevent conflicts with Controller class name conflict!
- 11.2. All models inherit directly or indirectly from the CI_Model class. The first letter of the class name is capitalized
- 11.3. The methods required for creation: getAll()...
- 11.4. Loading in the controller Model: $this->load->model("model file name"); //No suffix
- 11.5. Alias when loading the model in the controller: $this->load->model ("Model file name", "Alias");
- After successful loading, it will be placed in the properties of the super object. The default property name is the model file name or alias
- 11.6. Call the model in the controller. Get data: $this->Model file name->Method name();
- For example: $this->load->model("User_model"); //Pay attention to the case
- $this->User_model->getAll(); //Call the model and get the data
- 11.6.1. Call the model in the controller and get the data: $this->alias->Method name() ;
- For example: $this->load->model("User_model","user"); //Pay attention to the case
- $this->user->getAll(); / / Call the model and get the data
- 12. URL related functions in CI
- 12.1. Loading helper function: $this->load->helper("url");
- Configure automatic loading Helper function: Configure
-
$autoload['helper'] = array('url');
- in application/config/autoload.php, so there is no need to write $this- >load->helper("url");
- Helper function:
- site_url("Controller/Action/Parameters"); //Process url and parameters
- Use in the view
- base_url(); //Return to the root directory of the website ("ci/");
- 13. in CI Routing and pseudo-static, hidden index.php entry file
- 13.1, routing settings
-
- Set/modify in application/config/routes.php:
-
$route ['default_controller'] = "welcome"; //The default controller is welcome
-
- 13.2, pseudo-static setting
- is set in application/config/routes.php/ Modification:
- //regular matching (controller/)
-
$route['news/[d]{6}/([dw ]+).html']
= 'user/show/$1';
- http://localhost/CI/index.php/news/201401/caolizhi66.html
- will action The parameters in news are routed to user/show/$1
- 13.3. Hide the entry file index.php
- 13.3.1. Open the apache configuration file: LoadModule rewrite_module modules/mod_rewrite.so
- 13.3.2. In the entry file statistics directory, create a .htaccess file with the following content:
- RewriteEngine on //Enable pseudo-static
- RewriteCond %{ REQUEST_FILENAME} !-d //Match non-existing directories
- RewriteCond %{REQUEST_FILENAME} !-f //Match non-existent files
- RewriteRule ^(.*)$ index.php/$1 [QSA, PT,L] //Rewrite the rules
- This way you don’t have to write the entry file index.php
- 14. Pagination in CI
-
$this->load->library('pagination');
-
1 $config['base_url'] = $url;
- 2 / * Basic URL for paging
- 3 If you want to use the link form of a and b, the url should be in the form of /news/page/
- 4 If the link is in the form of c and d, the url should be in the form of /news?
- 5 */
-
6 $config['total_rows'] = $total;//The total number of records, there is nothing to say about this, it is the total number of records you get from the database
-
7 $config['per_page'] = $pagesize; //Number of items per page.Well, there’s not much to say about this. . Set it yourself. The default is 10.
-
8 $config['page_query_string'] = TRUE;
-
9 /*Parameter form. Turning on true will automatically add &per_page=3 after your url. (This per_page is the default query character. Of course, you can also use $config['query_string_segment'] to set it yourself)
- 10 Therefore, the forms in c and d are generally localhost/news?&per_page =2 But it’s all the same, it doesn’t matter. The per_page of get is still 3
- 11 */
-
12 $config['first_link'] = 'Homepage';
// The first page displays
-
13 $config['last_link'] = 'last page';
// The last page displays
-
14 $config['next_link'] = 'next page>';
// The next page displays
-
15 $config['prev_link'] = '<Previous page';
// Previous page shows
- 16 $config['cur_tag_open'] = '<aclass="current">';
// Current page start style
-
17 $config['cur_tag_close'] = '</a> ';
-
18 /* Ending style of the current page. You can try these yourself.
- 19For example, I want the pagination number style of the current page to look better, with red fonts, etc. You can add csscode to current num_links
- ' ]
= 2;//The number of page numbers displayed before and after the current connection. This means that your current page is page 5
, then you can see pages -
3, 4, 5, 6, 7 . 22 $config['uri_segment
'-
]=4 ;23/*this It is used to determine the number of pages when you use link styles a) and b). 24 For example, the uri_segment of localhost/news/page/3 should be set to 3. localhost/news/title/page/3 This should be set to 425 */
-
26
$config- ['
-
use_page_numbers
'-
]= TRUE;27/*This is the difference between a) and b). When turned on, page will indicate the number of pages. false will indicate the number of records
The above introduces the simple use of CI framework, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31