1、基础:php
建立项目:conposer create-project topthink/think tp5 --prefer-dist
建立项目模块:php think build --module demo
访问未配置的路由:http://localhost/tp5/
上线时要关闭调试模式:'app_debug' => false, config.php
//建立母案文件须要继承controller类 use think\Controller; class Index extends Controller($name = '张三'){
public function index($name = '张三'){
$this->assgin('name',$name);//可在html输出{$name}为张三
return $this->fetch();
}
}
//建立数据表 -- 记录没试过 CREATE TABLE IF NOT EXISTS `think_data`( `id` int(8) unsigned NOT NULL AUTO_INCREMENT, `data` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;INSERT INTO `think_data`(`id`,`data`) VALUES (1,'thinkphp'), (2,'php'), (3,'framework');
//链接数据库 use think\Db; class Index extends Controller{ public function index(){ $data = Db::name('data')->find(); $this->assign('result', $data); return $this->fetch(); } }
2、URL和路由:html
一、url访问:正则表达式
标准的URL访问格式:http://serverName/index.php/模块/控制器/操做/参数名/参数/参数名2/参数2
传入参数还可使用:http://serverName/index.php/模块/控制器/操做?参数名=参数&参数名2=参数2
//提示:模块在ThinkPHP中的概念其实就是应用目录下面的子目录,而官方的规范是目录名小写,所以模块所有采用小写命名,不管URL是否开启大小写转换,模块名都会强制小写。
//若是你的控制器是驼峰的,那么访问的路径应为:.../hello_world/index class HelloWorld{ public function index(){} } //若是使用.../HelloWorld/index 则会报错:Helloworld不存在。必需要使用大小写的时候须要配置: 关闭URL自动转换(支持驼峰访问控制器):'url_convert' => false, config.php
二、隐藏index.htmlthinkphp
//隐藏路径中的index.php,须要在入口文件平级的目录下添加.htaccess文件(默认包含该文件) <IfModule mod_rewrite.c> Options +FollowSymlinks -Multiviews RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L] </IfModule> //接下来就可使用:http://tp5.com/index/index/hello 访问了 //若是使用的是Nginx环境:能够在Nginx.conf中添加: localtion/{ if(!-e$request_filename){ rewrite ^(.*)$ /index.php?s=/$1 last; break; } }
三、*定义路由:数据库
//路由定义文件:application/route.php 原来的url将会失效!变为非法请求! return ['hello/:name'=>'index/index/hello',];//此方法的 name参数必选!
return ['hello/[:name]'=>'index/index/hello'];//此方法的 name参数可选!
//动态定义路由:application/route.php use think\Route; Rroute::rule('hello/:name/:age','index/hello');//必选参数 Rroute::rule('hello/[:name]/[:age]','index/hello');//可选参数
四、路由参数app
//能够用来约束URL后缀条件等。.../hello/index.html有效 return [ 'hello/[:name]' => ['index/hello', ['method' => 'get', 'ext' => 'html']], ];
五、变量规则iview
//能够用正则表达式来限制路由参数的格式 return [ 'blog/:year/:month' => ['blog/archive', ['method' => 'get'], ['year' => '\d{4}', 'month' => '\d{2}']], 'blog/:id' => ['blog/get', ['method' => 'get'], ['id' => '\d+']], 'blog/:name' => ['blog/read', ['method' => 'get'], ['name' => '\w+']], ];
六、路由分组fetch
return [ '[blog]' => [ ':year/:month' => ['blog/archive', ['method' => 'get'], ['year' => '\d{4}', 'month' => '\d{2}']], //blog/archive ':id' => ['blog/get', ['method' => 'get'], ['id' => '\d+']], //blog/get ':name' => ['blog/read', ['method' => 'get'], ['name' => '\w+']], //blog/read ], ];