Home >Backend Development >PHP Tutorial >Introduction to ThinkPHP framework_PHP tutorial
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
//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
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
between
Tips for using templates Here is the rendering page! ! !
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
{__CONTENT__}