框架用起来不难,关键在于理解原理,深入其中。不太喜欢用框架,更喜欢原生态,如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