Home  >  Article  >  Backend Development  >  Introduction to ThinkPHP framework_PHP tutorial

Introduction to ThinkPHP framework_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:19:04887browse

Introduction to ThinkPHP framework

ThinkPHP is a free, open source, fast, simple object-oriented lightweight PHP development framework. It was founded in early 2006 and released under the Apache2 open source license. , was born for agile WEB application development and simplified enterprise application development. ThinkPHP has been adhering to the simple and practical design principle since its birth. While maintaining excellent performance and minimal code, it also pays attention to ease of use. It has many original functions and features. With the active participation of the community team, it has been continuously optimized and improved in terms of ease of use, scalability and performance. It has grown into the most leading and influential WEB application development framework in China, with many Typical cases ensure that it can be stably used for commercial and portal-level development.

ThinkPHP MVC-based PHP framework
M – Model Model Work: Responsible for data operations
V – View View (template) Job: Responsible for front page display
C – Controller controller (module) work: describe the function

Introduction to ThinkPHP core files
├─ThinkPHP.php Framework entry file
├─Common framework public files
├─Conf framework configuration file
├─Extend framework extension directory
├─Lang core language package directory
├─Lib core library directory
│ ├─Behavior core behavior library
│ ├─Core core base class library
│ ├─Driver built-in driver
│ │ ├─Cache built-in cache driver
│ │ ├─Db built-in database driver
│ │ ├─TagLib built-in tag driver
│ │ └─Template built-in template engine driver
│ └─Template built-in template engine
└─Tpl system template directory

#Project directory structure and description:
Home frontend application folder
├─Common project public file directory
├─Conf project configuration directory
├─Lang project language directory
├─Lib project library directory
│ ├─Action Action class library directory
│ ├─Behavior behavior library directory
│ ├─Model model library directory
│ └─Widget Widget class library directory
├─Runtime project runtime directory
│ ├─Cache template cache directory
│ ├─Data data cache directory
│ ├─Logs log file directory
│ └─Temp temporary cache directory
└─Tpl project template directory

ThinkPHP 3 MVC pattern and URL access
What is MVC
M -Model writes model classes to operate on data
V -View writes html files and renders the page
C -Controller writes class file (UserAction.class.php)
ThinkPHP’s MVC features
The writing is very flexible, only the view can be executed

Directory corresponding to ThinkPHP’s MVC
M project directory/application directory/Lib/Model
V project directory/application directory/Tpl
C project directory/application directory/Lib/Action
url access C
4 ways to access url
1.PATHINFO mode

http://domain name/project name/entry file/module name/method name/key 1/value 1/key 2/value 2

2.Normal mode

http://domain name/project name/entry file?m=module name&a=method name&key1=value1&key2=value2

3.REWRITE mode

http://domain name/project name/module name/method name/key1/value1/key2/value2

4. Compatibility mode

http://domain name/project name/entry file? s=module name/method name/key1/value1/key2/value2

ThinkPHP 3.1.2 output and model usage
ThinkPHP 3 output
a. Output in the page through PHP native output methods such as echo
b. Output through the display method
If you want to assign a variable, you can use the assign method
c. Modify the left and right delimiters
Do not modify the configuration items in the configuration file
‘TMPL_L_DELIM’=>'<{‘, //Modify the left delimiter
‘TMPL_R_DELIM’=>’}>’, //Modify the right delimiter

Model usage of ThinkPHP 3
The database needs to be operated in the form of new Model (table name) in the method
$m=new Model(‘User’);
$arr=$m->select();
‘DB_TYPE’=>’mysql’, //Set the database type
‘DB_HOST’=>’localhost’,//Set the host
‘DB_NAME’=>’thinkphp’,//Set the database name
‘DB_USER’=>’root’, //Set username
‘DB_PWD’=>”,            //Set password
‘DB_PORT’=>’3306′, //Set the port number
‘DB_PREFIX’=>’tp_’, //Set table prefix
You can also use the DSN method for configuration
‘DB_DSN’=>’mysql://root:@localhost:3306/thinkphp’,//Use DSN method to configure database information
If both methods exist at the same time, the DSN method takes priority

There is also a simple and practical model
M() is equivalent to new Model();
$m=M(‘User’);
$arr=$m->select();

You can use model instances to operate data. The operation work is generally to add, delete, modify and check the database CURD
Add -C Create $m->add()
Delete -D Delete $m->delete()
Change -U Update $m->save()
Check -R Read $m->select()

a. Templates can traverse arrays


1
2
3

                  <{$vo.id}>----<{$vo.username}>-----<{$vo.sex}>


b. We can enable page_trace
in the debugging function 1. Turn on the debugging function
//3. Turn on debugging mode (configure index.php in the main entry file)
define(‘APP_DEBUG’,true);
2. We need to set up the configuration file and enable page trace
‘SHOW_PAGE_TRACE’=>true,//To enable page Trace, $this->display() is required to display

CURD Features
Read data
Reading of data Read
$m=new Model(‘User’);
$m=M(‘User’);
select
$m->select();//Get all data and return it in array form
find
$m->find(2);//Get a single piece of data
getField(field name)//Get a specific field value
$arr=$m->where(‘id=2′)->getField(‘username’);
Create data
Adding data Create
$m=new Model(‘User’);
$m=M(‘User’);
$m->Field name=value
$m->add();
The return value is the new id number
Delete data
$m=M(‘User’);
$m->delete(2); //Delete the data with id 2
$m->where(‘id=2′)->delete(); //Same effect as above, also deletes the data with id 2
The return value is the number of affected rows
Update data
$m=M(‘User’);
$data['id']=1;
$data['username']=’ztz2′;
$m->save($data);
The return value is the number of affected rows

Query method
Ordinary query method
a. String
$arr=$m->where(“sex=0 and username=’gege’”)->find();
b. Array
$data['sex']=0;
$data['username']='gege';
$arr=$m->where($data)->find();
Note: This method defaults to an and relationship. If you use an or relationship, you need to add an array value
$data['sex']=0;
$data['username']='gege';
$data['_logic']='or';
Expression query method
$data['id']=array('lt',6);
$arr=$m->where($data)->select();
EQ equals
NEQ is not equal to
GT is greater than
EGT is greater than or equal to
LT is less than
ELT is less than or equal to
LIKE fuzzy query
$data['username']=array('like','%ge');
$arr=$m->where($data)->select();
NOTLIKE
$data['username']=array('notlike','%ge%'); //There is no space in the middle of notlike
$arr=$m->where($data)->select();

Note: If a field needs to match multiple wildcards
$data['username']=array('like',array('%ge%','%2%','%五%'),'and');//If there is no third value, the default The relationship is or relationship
$arr=$m->where($data)->select();
BETWEEN
$data['id']=array('between',array(5,7));
$arr=$m->where($data)->select();
//SELECT * FROM tp_user WHERE ( (id BETWEEN 5 AND 7 ) )
$data['id']=array('not between',array(5,7));//Note that there must be a space between not and between
$arr=$m->where($data)->select();
IN
$data['id']=array('in',array(4,6,7));
$arr=$m->where($data)->select();
//SELECT * FROM tp_user WHERE ( id IN (4,6,7) )

$data['id']=array('not in',array(4,6,7));
$arr=$m->where($data)->select();
//SELECT * FROM tp_user WHERE ( id NOT IN (4,6,7) )
Interval query
$data['id']=array(array('gt',4),array('lt',10));//The default relationship is the relationship of and
//SELECT * FROM tp_user WHERE ( (id > 4) AND (id < 10) )

$data['id']=array(array('gt',4),array('lt',10),'or') //The relationship is the relationship of or

$data['name']=array(array('like','%2%'),array('like','%五%'),'gege','or');
Statistical query
count //Get the number
max //Get the maximum number
min //Get the minimum number
avg //Get the average
sum //Get the sum
SQL direct query
a. Query is mainly used for data processing
Result set of successfully returned data
Returns boolean false
on failure $m=M();
$result=$m->query(“select * from t_user where id >50″);
var_dump($result);
b. execute is used to update a write operation
Successfully returns the number of affected rows
Returns boolean false
on failure $m=M();
$result=$m->execute(“insert into t_user(username) values(‘ztz3′)”);
var_dump($result);

Continuous operation
Commonly used coherent operations
1.where
Help us set query conditions
2.order
Sort results
$arr=$m->order(‘id desc’)->select();
$arr=$m->order(array(‘id’=>’desc’,’sex’=>’asc’))->select();
3.limit
Limit results
limit(2,5)
limit(‘2,5′)
limit(10)//limit(0,10)
4.field
Set query fields
field(‘username as name,id’)
field(array(‘username’=>’name’,’id’)
field(‘id’,true) //Get all fields except id
5.table
Set table name
6.group
Group
7.having

alias is used to define an alias for the current data table string
page is used to query paging (will be converted to limit internally) strings and numbers
join* is used to support joins for queries. Strings and arrays
union* for union support for queries strings, arrays and objects
distinct distinct support for queries boolean
lock Lock mechanism used for database Boolean value
cache is used to query the cache and supports multiple parameters (described in detail in the cache section later)
relation is used for relational queries (requires relational model extension support) string
validate is used for automatic data validation array
auto is used for automatic data completion array
filter is used for data filtering string
scope* is used to name the scope string, array

View
Use of templates
a. Rules
Under the template folder [TPL]/[Group Folder/][Template Theme Folder/] Folder with the same name as the module name [Index]/File with the same name as the method name [index].html (.tpl)
Change the suffix of the template file (modify the configuration file)
‘TMPL_TEMPLATE_SUFFIX’=>’.html’,//Change the template file suffix name
b. Modify the template file directory hierarchy
‘TMPL_FILE_DEPR’=>’_’,//Modify the template file directory level
c. Template theme
‘DEFAULT_THEME’=>’your’,//Set the default template theme
You need to create a new your folder under TPL as the template theme folder
How to dynamically modify the template theme?
1. Prepare a function in the background and modify the default template item in the config.php file
2. Pass the t=theme parameter through the url to modify different templates
‘DEFAULT_THEME’=>’your’,//Set the default template theme
‘TMPL_DETECT_THEME’=>true,//Automatically detect template themes
‘THEME_LIST’=>’your,my’,//List of supported template themes

Output template content
a.display
1. There are no parameters in display
$this->display();
2. Can take parameters
$this->display (other template files in this module folder);
$this->display(‘index2′);

$this->display (template files in other folders);
$this->display(‘Public:error’);//Note that you only need to have the Public folder and error.html in it under Tpl, and you do not need to have the Public module

$this->display (template file under the folder under other themes);//Need to enable theme support
$this->display(‘my:Index:index’);

$this->display(a url path);
$this->display(‘./Public/error.html’);

$this->display(‘./Public/error.html’,’utf-8′,’text/xml’);

$this->show($content);
3.fetch method
Get the content in the template file and return it as a string
$content=$this->fetch(‘Public:error’);
4.show method
No template file is needed, the template content can be output directly
$content=$this->fetch(‘Public:error’);
dump($content);
$content=str_replace(‘h1′,’i’,$content);
$this->show($content);
Assignment in templates
//$this->assign(‘name’,’Zhao Tongzheng’);
$this->name=’Zhao Tongzheng2′;
$this->display();
Template replacement
__PUBLIC__: will be replaced by the public directory of the current website, usually /Public/
__ROOT__: will be replaced with the address of the current website (excluding domain name)
__APP__: will be replaced by the URL address of the current project (excluding domain name)
__GROUP__: will be replaced by the URL address of the current group (excluding domain name)
__URL__: will be replaced by the URL address of the current module (excluding domain name)
__ACTION__: will be replaced by the URL address of the current operation (excluding domain name)
__SELF__: will be replaced with the current page URL

Replace template variable rules and modify configuration items
‘TMPL_PARSE_STRING’=>array(​​​​​ //Add your own template variable rules
‘__CSS__’=>__ROOT__.’/Public/Css’,
‘__JS__’=>__ROOT__.’/Public/Js’,
),

Variables in templates
Variable output
1. Scalar output
2. Array output
{$name[1]} //Index array
{$name['k2']} //Associative array
{$name.k1}
3. Object output
{$name:k}
{$name->k}
System variables
{$Think.get.id}
Use function
The compiled file generated by {$name|strtoupper} is
{$name|date=’Y m d H:i:s’,###}
Default value
{$name|default=’This is the default value’}
Operator
+ – * / % ++ —
{$name++}

Basic syntax in templates
Import CSS and JS files
1. css link
js scr


2.import
//Import the test.js file in the Js directory under the Public folder. The type attribute can be omitted in the import tag. The default is js

//You can change the default folder and set the basepath attribute

3.load
//Method can automatically detect the imported file type

Branch structure
1. if

Men are made of mud

Women are made of water


Underage

Youth

Adult

> gt
< lt
== eq
<= elt
>= egt
!= neq
=== heq
!== nheq


A monk carries water to eat
Two monks eating Taiwan water
Three monks have no water to eat
Here is the default value

Loop structure
1.for





{$j}abc

2.volist

{$v.username}


3.foreach

{$k}——-{$v}


Special tags
1. Compare tags
eq or equal is equal to
neq or notequal is not equal to
gt is greater than
egt greater than or equal to
lt is less than
elt less than or equal to
heq is always equal to
nheq is not always equal to

2. Range tag
in
Inside these numbersNot within the range of these numbers
Within these numbersNot within the range of these numbers
between
‘TMPL_R_DELIM’=>’}>’, //Modify the right delimiter

Tips for using templates
Template contains







Use [variable] to accept variables in templates

Template rendering
1. Automatically turn on template rendering and set the configuration file
‘LAYOUT_ON’=>true,//Enable template rendering
Prepare a template rendering page and use {__CONTENT__} in the page to accept the content of the specific template page
If you do not want to use the rendering template in a specific template, you can add {__NOCONTENT__}
at the top of the page 2. If you do not enable automatic template rendering, you can add
at the top of each specific page.
3. Usage skills
The content of other template files can also be used in the rendering template file


Here is the rendering page! ! !


{__CONTENT__}


Template inheritance

Controller modules and operations
Empty modules and empty operations
1. Empty operation
function _empty($name){
$this->show(“$name does not exist Return to homepage”);
}
2. Empty module
class EmptyAction extends Action{
function index(){
$city=M(‘City’);
$arr=$city->select();
$this->assign(‘list’,$arr);
$name=MODULE_NAME;
$this->display(“City:$name”);
}
}

Pre-operation and post-operation
1. Pre-operation: _before_operation name
2. Post operation: _after_ operation name

URL
URL rules
1. The default is case-sensitive
2. If we don’t want to be case sensitive, we can change the configuration file
‘URL_CASE_INSENSITIVE’=>true,//url is not case sensitive
3. If the module name is UserGroupAction
Then the url to find the module must be written as

http://localhost/thinkphp4/index.php/user_group/index

4. If 'URL_CASE_INSENSITIVE'=>false
Then the url can also be written as

http://localhost/thinkphp4/index.php/UserGroup/index

URL pseudo-static
‘URL_HTML_SUFFIX’=>’html|shtml|xml’, //Limit pseudo-static suffix
URL routing
1. Start routing
To enable routing support in the configuration file
2. Use routing
1. Rule expression configuration routing
‘my’=>’Index/index’,//Static address routing
‘:id/:num’=>’Index/index’,//Dynamic address routing
‘year/:year/:month/:date’=>’Index/index’,//Dynamic and static mixed address routing
‘year/:yeard/:monthd/:dated’=>’Index/index’,//Dynamic and static mixed address routing
Adding d means that the type can only be numbers
‘my/:id$’=>’Index/index’,// Add $ to indicate that the address can only be my/1000 and there can be no other content after it
2. Regular expression configuration routing
‘/^year/(d{4})/(d{2})/(d{2})/’=>’Index/index?year=:1&month=:2&date=:3′
3. Notes:
1. The more complex routes are placed in front
‘URL_ROUTE_RULES’=>array(
‘my/:year/:month:/:day’=>’Index/day’,
‘my/:idd’=>’Index/index’,
‘my/:name’=>’Index/index’,
)
2. You can use $ as an exact matching routing rule
‘URL_ROUTE_RULES’=>array(
‘my/:idd$’=>’Index/index’,
‘my/:name$’=>’Index/index’,
‘my/:year/:month:/:day$’=>’Index/day’,
),
3. Use regular matching
‘URL_ROUTE_RULES’=>array(
‘/^my/(d+)$/’=>’Index/index?id=:1′,
‘/^my/(w+)$/’=>’Index/index?name=:1′,
'/^my/(d{4})/(d{2})/(d{2})$/'=>'Index/day?year=:1&month=:2&day=:3′,
),

URL Rewriting
URL generation

Grouping, page jump and ajax
Multi-application configuration tips
Use grouping
Page jump
$this->success(‘query successful’,U(‘User/test’));
$this->redirect(‘User/test’,”,5,’The page is jumping’);
Ajax skills
Big C method to get the array name and value in the configuration file
echo C(‘DB_USER’);

Big F method file processing
Write: F(‘file name’, ‘array’, ‘directory’);
Read: F(‘file name’,”,’directory’);

Big U method URL processing
In PHP
U(‘method name’)
In template
Current function {:U(‘method name’)}
Other functions {:U(‘function/method name’)}

*File import

*Form processing
Method 1 $this->_post(”);
To obtain the submission form, the function htmlspecialchars() will be used to filter
$username=$this->_post(‘username’);

Method 2 I(‘username’); [New features in 3.1.3]
Big I, automatically determines post and get
$username=I(‘username’);
echo I(‘username’, ‘Default value when no value exists’, ‘Use function’);

Check whether there is data submission:
print_r(I(‘post.’));

Prohibit access to form processing functions to improve security
Method 1
if(!$this->isPost()) _404(‘Page does not exist’, U(‘index’));
echo 'Normal submission';

Method 2 (recommended) The halt page can customize the error page:
if(!IS_POST) halt(‘Page does not exist’);
echo 'Normal submission';

Formulation method: Add: 'TMPL_EXCEPTION_FILE'=>'./Public/Tpl/error.html',
in Conf/config.php The file accepts error content: ./Public/Tpl/error.html, only native PHP can be written, and constants are supported, such as __APP__

//Return the inserted ID value, the database starts from 1
if(M(‘user’)->data($data)->add()){
$this->success(‘Add successfully’,’index’);
}else{
$this->error(‘Add failed’);
}

*Output to template

1, Data preparation
Method 1
$this->assign(‘Variable name’, ‘Variable value’)

Method 2
$this->Variable name=’Variable value’;

Method 3 (new version, shortened code)
$this->assign(‘Variable name’, ‘Variable value’)->display();

Method 4 (one line)
$this->assign(‘data’,M(‘User’)->select())->display();

2, template output
Method 1 (. The syntax will determine whether it is an object or an array. Configuration parameter: TMP_VAR_IDENTIFY=>'array', so it will be considered an array to improve speed)

{$v.username}—{$v.password}—{$v.time|date=’y-m-d H:i:s,###’}

Use function {:phpinfo()}

Method 2
volist

*Grouped applications (application groups) only use one entry file for the front and backend
idnex.php (default)
define(‘APP_NAME’,’App’);
define(‘APP_PATH’,’./App/’);
define(‘APP_DEBUG’,’TRUE’);
require ‘./ThinkPHP/ThinkPHP.php’;
?>

App/Conf/config.php
return array(
//Enable grouping
‘APP_GROUP_LIST’=>’Index,Admin’,
‘DEFAULT_GROUP’=>’Index’,

‘TMPL_FILE_DEPR’=>’_’, //The default template delimiter is _ instead of folder format
);

Custom controller
1. Delete the original default controller in the Action folder
2. Create two folders, namely the frontend and the backend such as Index Admin
Visit: Frontend host/index.php/Index Backend host/index.php/Admin

Customized configuration files (cannot access each other, but public configurations can access each other)
1. Create two folders in host/App/Conf/, namely the frontend and the backend such as Index Admin
Configuration: Frontend host/App/Conf/Index/config.php
Backend host/App/Conf/Admin/config.php

Custom function
1. Create two folders in host/App/Common/, namely the frontend and the backend such as Index Admin
Configuration: Frontend host/App/Common/Index/function.php
Backend host/App/Common/Admin/function.php

Note: Grouped applications do not support the direct use of {:U("form_save")}, that is, the current method of the current controller, written like this:
{:U(“/Index/Index/form_save”)}
*Group application [Complete]

**Independent grouping configuration
Turn on:
1. First configure the application group
2. Add parameters
‘APP_GROUP_MODE’=>1, //Enable independent grouping
‘APP_GROUP_PATH’=>’Modules’, //Default group path, default: Modules

Commonly used path variables: __ROOT__.’/’.APP_NAME.’/’.C(‘APP_GROUP_PATH’).’/’.GROUP_NAME.’/’
New directory structure:
ThinkPHP //System directory
App //Project Directory
Public //Static file directory
index.php //Entry files for all projects

App:
Modules //Project module ==>Admin/Action,Tpl,Model,Conf,Common; Index/Action,Tpl,Model,Conf,Common;
Common //Public Common
Conf //Public Conf
Lib //Public Lib
Tpl //Public Tpl
Runtimes //Runtime

Public:
css js img

**JQuery asynchronous submission
$(‘#send-btn’).click(
function(){
var username=$(‘input[username=username]‘);
var password=$(‘input[password=password]‘);

if(username.val()==”){
alert(‘Username cannot be empty’);
username.focus();
//Let username get focus
return;
}

if(password.val()==”){
alert(‘Password cannot be empty’);
password.focus();
//Let username get focus
return;
}

//Start asynchronous transmission (php must be parsed within the template, not in a separate js file)
var sendUrl='{:U("Index/Index/form_save",",")}';

$.post(sendUrl,{username:username.val(),password:password.val()},function(data){},’json’);
}
);

**php asynchronous form processing:
Public function form_save(){
//var_dump($this->isAjax()); //Determine whether there is data submitted
//var_dump(IS_AJAX); //[New version] Determine whether there is data submission
if(!$this->isAjax()) halt (‘Page does not exist’);
$data=array(
‘username’=>$this->_post(‘username’),
‘password’=>$this->_post(‘password’),
‘time’=>time()
);
//p($data);

}

No records since class 11

*Introduction module
1. The verification code module is not included in the core package. It needs to be added manually and placed in ThinkPHP/Extend/Library/ORG/Util/Image.class.php
import(‘ORG.Util.Image’);
Image::BuildImageVerify(4,5,’png’);
Access: This method address is enough
Change the verification code and use a JS random number function: Math.random();
Note: If a pseudo-static suffix appears, you need to add 2 empty parameters
in {:U(‘Admin/Login/index’),”,”} Mixed modes are case sensitive

Verification code background verification
if(md5($_POST[code])!= session('verify')){ $this->error('Verification code error');}
if(md5($this->_post[code])!= session('verify')){ $this->error('Verification code error');}
if(I('code','','md5')!= session('verify')){ $this->error('Verification code error');}

2, paging class
import('ORG.Util.Page'); //Import class
$max=M('User')->count(); //Query the total number of items
$page=new Page($max,5,'','Index/Index/index/p/');
//Instantiate the object, parameters: 1 total number of items, 2 number of items per page, 3 page jump parameters, 4 set URL path, useful when grouping, because there are few application group names
$limit=$page->firstRow.','.$page->listRows; //Get the first page and the total number of pages and set them as limit value
$m=M('User')->order('time DESC')->limit($limit)->select(); //Find the data on the first page
$this->User=$m; //Assign data to the front-end template for foreach traversal
$this->page=$page->show(); //Assign paging content to the frontend template

Pagination data call in template: {$page}

**SESSION Save to database
1. Add configuration file: 'SESSION_TYPE'=>'Db',

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/878455.htmlTechArticleIntroduction to ThinkPHP framework ThinkPHP is a free and open source, fast and simple object-oriented lightweight PHP development framework , founded in early 2006, released under the Apache2 open source license, is...
Statement:
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