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 ], ];