thinkphp笔记
thinkphp 笔记
TP框架:
1.模板引擎
2.MVC设计模式
3.常用操作类
模板引擎和框架区别:
1.模板引擎只是框架中用来做php和html分离的
MVC设计模式:
M 数据模型
V 视图
C 控制器
V(HTML模板) --smarty()--》 C(PHP逻辑控制) -》M(Model类表操作)
localhost/test/index.php/模块/操作
localhost/test/index.php/Index/add
目录结构
ThinkPHP.php 框架入口文件
Common 框架公共文件目录
Conf 框架配置文件目录
Lang 框架系统语言目录
Lib 系统核心基类目录
Tpl 系统模板目录
Extend 框架扩展目录
//入口文件定义 index.php
define('APP_NAME',"Home");
define('APP_PATH',"./Home/");
define('APP_DEBUG',true);
include "ThinkPHP/ThinkPHP.php";
TP访问地址:
http://localhost/test/index.php/Index/index
TP访问地址参数:    
http://localhost/test/index.php/Index/index/id/10 pathinfo地址模式
http://localhost/test/index.php/Index/index?id=10
改变左右定界符   ThinkPHP/Conf/convention.php
'TMPL_L_DELIM'   => '<{',
'TMPL_R_DELIM'   => '}>',
会被所有应用共享配置文件
localhost/test/index.php/Index/index/
__ROOT__ = /test
__APP__  = /text/index.php
__URL__  = /test/index.php/Index
__ACTION__ = /test/index.php/Index/index
__SELF__ =/test/index.php/Index/index/id/10
__PUBLIC__ =/test/Public
../Public = /test/Home/Tpl/Public
__TMPL__ =/test/Home/Tpl 	
php中可以使用的路径常量:
__ROOT__
__APP__
__URL__
__ACTION__
__SELF__
模板中可以使用的路径模板替换:
__ROOT__
__APP__
__URL__
__ACTION__
__SELF__
__PUBLIC__
../Public
__TMPL__
注意:静态资源一定要用网站绝对路径
C("DB_PORT")//直接获取配置文件里面的值
//改变默认的地址模块:
Home/Conf/config.php
return array(
'DEFAULT_MODULE'=>'User',	
);
Home/Common/common.php
写到他里面的函数,可以在本应用中所有模块的操作中使用
包含扩展类:
import("ORG.Util.Image");//包含ThinkPHP/Extend/Library/ORG/Util/Image.class.php
_initialize()//初始化方法  登录权限把控的时候用
//CommonAction.class.php
专门建一个类 class CommonAction extends Action{
	function _initialize(){
		echo "权限把控";
	}
}
//LoginAction.class.php
class LoginAction extends Action{
	function index(){
		echo "登录";
	}
}
//UserAction.class.php
Class UserAction extends CommonAction{
	public function index(){
		echo "test";
	}
}
综上,只有login不继承commonaction,其他所有的类都继承commonaction,这样自动触发
		  login 继承Action
Thinkphp支持的四种URL模式
1.普通模式
http://localhost/test/index.php?m=Index&a=index
2.pathinfo
http://localhost/test/index.php/Index/index
3.rewrite模式
http://localhost/test/Index/index
rewrite方式来访问模式和操作:
1).apache必须支持mod_rewrite.so模块
   LoadModule rewrite_module modules/mod_rewrite.so
2).www网站根目录支持解析rewrite重写表达式文件  .htaccess
<Directory "C:/AppServ/www">
	Options Indexes FollowSymlinks ExecCGI
	AllowOverride All
	Order allow,deny
	Allow from all
</Directory>
注意:options 不能出现Multiviews,AllowOverride 后必须写ALL
3)..htaccess里面书写的rewrite表达式
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME}% !-d
RewriteCond %{REQUEST_FILENAME}% !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>
4.兼容模式
http://localhost/test/?s=Index/index
a标签  不能用 href=__URL__/show
要用:U(); a href="<{:U()}>/show"
这种方式对网站的SEO优化最好
U有三个参数   U("show","","html")第一个参数是模块/方法,第二个参数是传参,第三个参数是后缀,第四个是否跳转到那个页面
一般跳转不用第四个参数  一般用$this->redirect();
或者$this->success('yes',U('show'),5);//有倒计时的跳转
	$this->erroe('no',U('show'),5);
如果要在模板中使用php函数,要在函数前面加冒号
:time()   :strtoupper()
调试模式下 自定义报错页面
Home/Conf/config.php
'TMPL_EXCEPTION_FILE' => './Public/error.html',
在操作中获取当前地址中的模块和方法
1.$_GET[_URL_][0] 当前模块
  $_GET[_URL_][1] 当前方法
2.MODULE_NAME 模块名
  ACTION_NAME 方法名
常用常量:
MODULE_NAME
ACTION_NAME
IS_GET
IS_POST
IS_AJAX
__ROOT__ 网站根目录地址  
__APP__ 当前项目(入口文件)地址  
__GROUP__ 当前分组的URL地址  
__URL__ 当前模块的URL地址  
__ACTION__ 当前操作的URL地址  
__SELF__ 当前URL地址  
__INFO__ 当前的PATH_INFO字符串  
__EXT__ 当前URL地址的扩展名  
空模块
EmptyAction.class.php
空操作
_empty()
URL伪静态   省略index.php   地址后面的静态后缀
			'URL_HTML_SUFFIX' => 'html'
URL路由	
URL重写
URL生成
跨模块调用:
$test = A('user');  //user模块
$test -> index();  //user模块下的index方法
R('user/index') //user模块下的index方法 直接调用
Thinkphp 数据库的add方法!!!!!!!!!!  
调用了htmlspecialchars  还有  mysql_escape_string  //这块要自己测试!!!  否则插入得数据可能多一个反斜线
例如 <b>aaa</b>\"\"  =>  <b>aaa</b>\\"\\"
如果不想这样 只需要修改DbMysql.class.php
328行
public function escapeString($str)
{
	if(get_magic_quotes_gpc()){
		return $str;
	}
	if($this -> _linkID)
	{
		return mysql_real_escape_string($str,$str->_linkID);
	}
	else
	{
		return mysql_escape_string($str);
	}
}
AJAX
$this -> ajaxReturn($arr,"aaa",'1')
					数据  信息  状态
$.post(,function(rtn){
	//alert(rtn.data.username);
	var str = '';
	for(var i in rtn.data)
	{
		str += i+"=>"+rtn.data[i];
	}
	$("#main").html(str);
})
M方法是默认的Model类
D方法是自定义Model类 如果没有就用系统的基类
查看model类的sql语句
echo $model->getLastSql();
//设置model类在组合时真实的表名
protected $tableName = 'user';
//获取主键
$user->getPk();
$model->create();
//生成model对象中的数据对象data,他可以智能过滤post表中字段不相符的下标
//自动验证 UserModel类里 protected $_validate = array(); 出错的话用$user->getError(); 来获取错误 
	if($user -> create())
	{
		$user -> add();
	}
	else
	{
		echo $user -> getError();
	}
UserModel.class.php:
protected $_validate =  array(
	array('username','requite','用户名不能为空'),
	array('fcode','requite','验证码不能为空'),
	array('password','requite','密码不能为空'),
	array('repassword','password','两次密码不一致',2,'confirm'),
	array('fcode','checkCode','验证码有误',2,'callback'),
);
function checkCode($fcode)
{
	if($fcode!=$_SESSION['scode'])
	{
		return false;
	}
}
protected $patchValidate = true;//新版支持数据的批量验证功能,只需要在模型类里面设置patchValidate属性为true( 默认为false),设置批处理验证后,getError() 方法返回的错误信息是一个数组
//自动完成 UserModel类里 protected $_auto = array();
//字段映射
添加数据两种方法
1.
	$_POST['username'] = 'user5';
	$_POST['password'] = '456';
	$_POST['regtime'] = time();
	$user = M('User');
	$user -> add($_POST);
2.
	$_POST['username'] = 'user5';
	$_POST['password'] = '456';
	$_POST['submit'] = '提交';
	$user = M('User');
	$user -> create();
	$user -> regtime = time();
	$user -> add();
curd操作
insert:     (add)
1.$model -> add();//$model->add($_POST);
2.$model -> create(); 
  $model -> add();
update:		(save)
1.$user = D('User');
  $user->save($_POST);
2.$user = D('User');
  $user -> create();
  $user -> save($_POST);
select:		(select)
			(find)
	$rows = $user -> select($id);//多个结果 二维数组
	$rows = $user -> find($id);//单个结果 一维数组
	$rows = $user -> where("id=$id") -> find();
	排序id $rows = $user -> where("id = $id") -> order('id') ->find();
delete:		(delete)
	$model -> delete($id);
	$model -> where("id = $id") -> delete();
连贯操作
mysql左连接  
一个用户表			成绩表
	user1			70
	user2			80
	user3			NULL
	user4			NULL
要查所有人的成绩,缺考的补0 不能用select user.username,score.num from user,score where user.id = score.uid; //返回的只有user1 和user2
要用左连接
select user.username,if(score.num,score.num,0) from user left join score on user.id = score.uid
left join on 后不能用and 要用where
例如:select user.username,score.num from user left join score on user.id = score.uid where score.num is not null;
模板布局
{__CONTENT__} //替换为原来模板  现在模板是layout.html 
控制器关联模型
用户表-user
电话表-tel
班级表-class
IndexAction / index
$user = D('User')
$rows = $user -> relation('teltab') -> select();
$rows = $user -> relation(true) -> select();//true全映射,false不映射
//注意:中间的不是真实的表名而是映射的表名 -- mappingname
UserModel:
protected $_link=array(
	'mapping_type' => HAS_MANY,
	'class_name' => 'Tel',
	'foreign_key' => 'user_id',
	'mapping_name' => 'teltab',
	'mapping_fields' => 'code',
)
师徒:
跨膜版 display(Test:show)
$str = $this -> fetch('Test:index')
模板引擎:
$Think.now  时间  $think.const//define('HOST','a') 常亮
调用函数
<{$name|strtoupper}>
<{$time|date='Y-m-d H:i:s',###}>//date("Y-m-d H:i:s",time())
$this->time= time();
模板for循环 else一定要加/
include包含文件
<include file='public:header'/>
包含header.html
$CIP = get_client_ip()//得到用户IP
$ips = $IP -> getlocation($CIP)//知道用户在哪个区
<import> 导入css,js
模板继承
快捷缓存(数据缓存) cache S
	if($!('rows'))
	{
		$user = M('User');
		$rows = $user -> select();
		S('rows',$rows);
	}
	$this -> rows = S('rows');
	$this -> display()
静态缓存(模板缓存)
	'HTML_CACHE_ON' = true,
	'HTML_CACHE_RULES' = array(
	'*' => array('{:module}/{:action}'),//所有模板所有页面缓存
	'*' => array('{$_SERVER.REQUEST_URL|md5}') //等于上面
	)
session支持:
	session('username','user1')
	session('login','1')
	session('isadmin','1')
删除session三步:
	删除本地session数组
	删除服务器session文件
	删除客户端cookie
	session(null);
    session('[destroy]');
    cookie(session_name(),null);
中文验证码:
需要有字体支持
字体文件放在ThinkPHP/Extend/Library/ORG/Util
表单提交: //自动验证
$user = D('user');
if($user -> create()){
	$user -> add();
}
else
{
	echo $user->getError();
}
水印函数:
import('ORG.Util.Image');
$img = new Image();
$path = './Public/Uploads/Images/';
$src = $path.'a.jpg';
$dst = $path.'loao.png';
$save = $path.'w_a.jpg';
$img -> water($str,$dst,$save);
图片缩放:
thumb($image,$thumbname,$type='',$maxWidth=200,$maxHeight=50,$interlace=true);
$img -> thumb;
数据分页:
$user = M('User');
import('ORG.Util.Page');
$count = $user -> count();
$length = 3;
$page = new Page($count,$length);
$this->show = $page -> show();
$this->rows = $user->order('id') -> limit($page -> firsRow,$length)->select();
$page->setConfig("theme","总计%totalRow%个用户 %upPage% %%downPage");//这样可以自己定制格式
文件上传:
$up = new UploadFile();
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号