Home  >  Article  >  Backend Development  >  thinkphp notes, thinkphp_PHP tutorial

thinkphp notes, thinkphp_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:44:50975browse

thinkphp notes, thinkphp

M project directory/application directory/Lib/Model V Project Directory/Application Directory/Tpl C project directory/application directory/Lib/Action 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 module http://domain name/project name/module name/method name/key 1/value 1/key 2/value 2 4. Compatibility mode http://domain name/project name/entry file? s=module name/method name/key 1/value 1/key 2/value 2 // This class is automatically generated by the system and is for testing purposes only
class IndexAction extends Action {
public function index(){
echo "hello world";
}
public function add(){
echo "Hello, Wu Hao
";
echo 'Hello'.$_GET['name'].'Your age is'.$_GET['age'];
}
}
http://localhost/test/index.php/Index/add?name=wuhao http://localhost/test/index.php/Index/add/name/wuhao http://localhost/test/index.php/Index/add/name/wuhao/age/18

'URL_PATHINFO_DEPR'=>'-', //Modify the URL delimiter

'TMPL_L_DELIM'=>'<{', //Modify the left delimiter 'TMPL_R_DELIM'=>'}>', //Modify the right delimiter http://localhost/test/index.php/Index-add-name-wuhao-age-23 http://localhost/test/index.php/Index/index
http://localhost/test/index.php/Index/add public function add(){ /*echo "Hello, Wu Hao
";
echo 'Hello'.$_GET['name'].'Your age is'.$_GET['age'];*/ $name='Wu Hao'; $this->assign('myname',$name); //$this->myname='abc'; $this->display(); }
Some dynamic data can be assigned to template display through the assign() method

Accessed the add method.

Hello! {$myname}

D:wampwwwtestAppTplIndex You need to operate the database 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 user name 'DB_PWD'=>'', //Set password 'DB_PORT'=>'3306', //Set the port number 'DB_PREFIX'=>'tp_', //Set table prefix 'DB_DSN'=>'mysql://root:@localhost:3306/thinkphp',//Use the DSN method to configure database information, which has a higher priority than the traditional method
$user=new Model('User'); $arr=$user->select(); var_dump($arr); $this->display(); 'SHOW_PAGE_TRACE'=>true,//Open page Trace 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 {$vo.id}----{$vo.username}-----{$vo.sex}
b. We can enable page_trace in the debugging function 1. Enable debugging function define('APP_DEBUG',true); 2. We need to set up the configuration file and enable page trace 'SHOW_PAGE_TRACE'=>true,//Open page Trace 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($id); //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(); 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 CURD Demo: ================================================== ================================================== ================================================== =============================================== Query method: 1. Common query methods 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['_logic']='or'; 2. Expression query method $data['id']=array('lt',6); $arr=$m->where($data)->select(); EQ is equal to, 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%'); $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 relationship is the or relationship 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)); $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) ) 3. 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'); 4. Statistical query count //Get the number; max //Get the maximum number; min //Get the minimum number; avg //Get the average; sum //Get the total 5. SQL direct query a. Query is mainly used to process reading data: successfully returns the result set of the data, and fails to return boolean false $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, and fails to return boolean false $m=M(); $result=$m->execute("insert into t_user(`username`) values('ztz3')"); var_dump($result); 'DB_LIKE_FIELDS'=>'title|content' //The conditions in the query statement automatically become fuzzy query%% Query method demonstration: ================================================== ================================================== ================================================== =============================================== Commonly used coherent operations 1.where Help us set query conditions 2.order Sort the 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 field field('username as name,id') field(array('username'=>'name','id') field('id',true) //Get all fields except id 5.table 6.group 7.having 2. Supplement alias is used to define an alias string for the current data table 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 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 related queries (requires related model extension support) string validate is used for automatic data verification array auto is used for automatic data completion array filter is used for data filtering string scope* is used to name ranges strings and arrays ================================================== ================================================== ================================================== =============================================== View: 1. Use of templates a. Rules Under the template folder [TPL]/[Group Folder/][Template Theme Folder/] and the folder with the same name as the module name [Index]/the 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 hierarchy 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 to 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',//Supported template theme list http://localhost/test/index.php/Index/index/t/my http://localhost/test/index.php/Index/index/t/you 2. 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 files under folders 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 required, the template content can be output directly $content=$this->fetch('Public:error'); dump($content); $content=str_replace('h1','i',$content); $this->show($content); 3. Assignment in templates //$this->assign('name','Zhao Tongzheng'); $this->name='Zhao Tongzheng2'; $this->display(); 4. 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 Change 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', ), Login box example: Introduce the extension class and put the files in ThinkPHP3.1.2_Extend in the D:wampwwwtestThinkPHPExtend folder. Corresponding js and css: D:wampwwwtestPublicCss ·D:wampwwwtestPublicJs ================================================== ================================================== ================================================== =============================================== Variables in template: 1. Variable output 1. Scalar output 2. Array output {$name[1]} {$name['k2']} {$name.k1} 3. Object output {$name:k} {$name->k} 2. System variables
用法 含义 例子
$Think.server 获取$_SERVER {$Think.server.php_self}
$Think.get 获取$_GET {$Think.get.id}
$Think.post 获取$_POST {$Think.post.name}
$Think.request 获取$_REQUEST {$Think.request.user_id}
$Think.cookie 获取$_COOKIE {$Think.cookie.username}
$Think.session 获取$_SESSION {$Think.session.user_id}
$Think.config 获取系统配置参数 {$Think.config.app_status}
$Think.lang 获取系统语言变量 {$Think.lang.user_type}
$Think.const 获取系统常量 {$Think.const.app_name}或{$Think.APP_NAME}
$Think.env 获取环境变量 {$Think.env.HOSTNAME}
$Think.version 获取框架版本号 {$Think.version}
$Think.now 获取当前时间 {$Think.now}
$Think.template 获取当前模板 {$Think.template}
$Think.ldelim 获取模板左界定符 {$Think.ldelim}
$Think.rdelim 获取模板右界定符 {$Think.rdelim}
Usage
Meaning Example
$Think.server Get $_SERVER {$Think.server.php_self}
$Think.get Get $_GET {$Think.get.id}
$Think.post Get $_POST {$Think.post.name}
$Think.request Get $_REQUEST {$Think.request.user_id}
$Think.cookie GET $_COOKIE {$Think.cookie.username}
$Think.session Get $_SESSION {$Think.session.user_id}
$Think.config Get system configuration parameters {$Think.config.app_status}
$Think.lang Get system language variables {$Think.lang.user_type}
$Think.const Get system constants {$Think.const.app_name} or {$Think.APP_NAME}
$Think.env Get environment variables {$Think.env.HOSTNAME}
$Think.version Get the framework version number {$Think.version}
$Think.now Get the current time {$Think.now}
$Think.template Get the current template {$Think.template}
$Think.ldelim Get template left delimiter {$Think.ldelim}
$Think.rdelim Get template right delimiter {$Think.rdelim}
3. Use functions {$name|strtoupper} The compiled file generated is: {$name|date='Y m d H:i:s',###} 4. Default value {$name|default='This is the default value'} 5. Operators - * / % -- {$name } Basic syntax in templates: 1. Import CSS and JS files 1. 2.import //Import the test.js file in the Js directory under the Public folder. The import tag can omit the type attribute. 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 2. Branch structure Underage Youth Adult > gt < lt == eq <= elt >= egt != neq === heq !== nheq A monk carries water to eat Two monks eat Taiwan water Three monks have no water to eat This is the default value 3. Loop structure 1.for                                                                                                                                                
2.volist {$v.username}
3.foreach $user=M('User1'); $arr=$user->select(); $this->assign('list',$arr); $this->display();                                                                                                                                                                                                                                                                                                                                                                                                                            
4. Special tags 1. Compare tags eq or equal is equal to neq or notequal 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 heq is equal to nheq is not 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 {$n} is between 1-10{$n} is not between 1 and 10 3.present: tag to determine whether the template variable has been assigned a value, m has a value assignedm has no value assigned 4.Empty: The empty tag determines whether the template variable is empty, n is empty assignmentn has value 5.Defined: Determine whether the constant has been defined 6.Define: Define constants in templates 7.Assing: Assigning values ​​to variables in templates 5. Use of other tags 1. Use PHP code directly in the template echo "I am Zhao Tongzheng" 2. It is recommended to change the left and right delimiters Change in configuration file 'TMPL_L_DELIM'=>'<{', //Modify the left delimiter 'TMPL_R_DELIM'=>'}>', //Modify the right delimiter Tips for using templates: 1. Template contains Use [variable] to accept variables in templates: 2. 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 tips: You can also use the content of other template files in the rendering template file & lt; p & gt; This is the rendering page! ! !

{__CONTENT__} 3. Template inheritance ================================================== ================================================== ================================================== =============================================== Modules and operations of the controller: 1. Empty modules and empty operations 1. No 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"); } } 2. Pre-operation and post-operation 1. Pre-operation: _before_operation name 2. Post operation: _after_ operation name ================================================== ================================================== ================================================== =============================================== URL: 'URL_CASE_INSENSITIVE'=>true,//url is not case sensitive 'URL_HTML_SUFFIX'=>'html|shtml|xml',//Restrict pseudo-static suffix 1. 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
2. URL Pseudo-static
'URL_HTML_SUFFIX'=>'html|shtml|xml', //Restrict pseudo-static suffix
3. URL routing
1. Start routing
To enable routing in the configuration file Support
2. Use routing
1. Configure routing with regular expressions
'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
Add d to represent that the type can only be a number
'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. More For complex routes, place
'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 method
'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',
),
4. URL rewriting
5. URL generation
Page jump $this->success('Query successful',U('User/test')); $this->redirect('User/test','',5,'The page is jumping'); 'APP_GROUP_LIST' => 'Home,Admin', //Project group setting 'DEFAULT_GROUP' => 'Home', //Default group ================================================== ================================================== ================================================== ===============================================

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1045058.htmlTechArticlethinkphp notes, thinkphp M project directory/application directory/Lib/Model V project directory/application directory/Tpl C project Directory/Application Directory/Lib/Action 1.PATHINFO mode http://domain name/project name/entry...
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