框架用起來不難,關鍵在於理解原理,深入其中。不太喜歡用框架,更喜歡原生態,如wordpress般,亂且爽,但wordpress太深。框架用在多人開發,快捷開發,高效。
參考thinkphp快速入門
1.在www目錄下創建測試目錄tp_demo,並粘貼thinkphp到該目錄下
2. 創建入口文件如index.php
define('APP_DEBUG', TRUE); //開啟調試
define('APP_NAME', 'home'); //配置項目名
define('APP_PATH', './home/'); //項目目錄
require_once "ThinkPHP/ThinkPHP.php"; //引入tp
3.http://127.0.0.1/tp_demo/ 以實際目錄為准,默認走APP_PATH目錄下Lib/Action/IndexAction.class.php
關於URL訪問路徑有以下幾種方式:
普通模式
http://127.0.0.1/tp_demo
http://127.0.0.1/tp_demo/index.php?m=Index
http://127.0.0.1/tp_demo/index.php?m=Index&a=index
PATHINFO模式
http://127.0.0.1/tp_demo/index.php/Index/index
REWRITE模式,以apache為例,修改對應目錄下的.htaccess文件
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>
兼容模式
http://127.0.0.1/tp_demo/?s=/Index/index
測試:APP_PATH/Lib/Action/TestAction.class.php
class TestAction extends Action { public function index(){ echo '默認入口'; } public function test(){ echo '指定入口'; } }
分別對應URL:http://127.0.0.1/tp_demo/?m=Test&a=index(a=index可省略)t、http://127.0.0.1/tp_demo/?m=Test&a=test,注意Test大小寫。
4.模板
class TestAction extends Action { public function show(){ $this->var = 'hello world'; //模板變量賦值,模板文件中以{$var}表示 //默認到項目目錄下的tpl下Test目錄下show.html文件 //$this->display(); //指定文件名 //$this->display('test'); //指定到dir目錄下的test.html文件 $this->display('dir/test'); } }
5.讀取數據,直接copy官網例子
5.1 建表,插入測試數據
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');
5.2 修改配置文件,APP_PATH/\Conf\config.php
return array( // 添加數據庫配置信息 'DB_TYPE' => 'mysql', // 數據庫類型 'DB_HOST' => 'localhost', // 服務器地址 'DB_NAME' => 'test', // 數據庫名 'DB_USER' => 'root', // 用戶名 'DB_PWD' => '', // 密碼 'DB_PORT' => 3306, // 端口 'DB_PREFIX' => 'think_', // 數據庫表前綴 //數據庫類型://用戶名:密碼@數據庫地址:數據庫端口/數據庫名。如果兩種配置參數同時存在的話,DB_DSN配置參數優先。 'DB_DSN' => 'mysql://root:123456@localhost:3306/test' );
class TestAction extends Action { public function showData(){ $Data = M('Data'); // 實例化Data數據模型,用M方法實例化模型不需要創建對應的模型類,你可以理解為M方法是直接在操作底層的Model類,而Model類具備基本的CURD操作方法。 $this->data = $Data->select(); $this->display(); } }
添加APP_PATH/tpl/Test/showData.html模板
<html> <head> <title>Select Data</title> </head> <body> <volist name="data" id="vo"> <!--類似於smarty中的<{foreach}>,循環--> {$vo.id}--{$vo.data}<br/> <!--{$arr.$key}輸出數組的值--> </volist> </body> </html>
?m=Test&a=showData 輸出如下:
1--thinkphp
2--php
3--framework