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();
轉載于:https://www.cnblogs.com/Duskcl/p/5037552.html
總結
以上是生活随笔為你收集整理的thinkphp笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开发环境配置--Ubuntu+Qt4+O
- 下一篇: 时光飞逝