本文實例講述了從ThinkPHP3.2.3過渡到ThinkPHP5.0學(xué)習(xí)筆記。分享給大家供大家參考,具體如下:
用tp3.2.3做了不少項目,但是畢竟要與時代接軌,學(xué)習(xí)一些新的框架,比如tp5
以下記錄一些學(xué)習(xí)中遇到的問題及解決辦法,還有tp3.2和tp5.0的一些區(qū)別,適合給用過tp3沒用過tp5的童鞋做個參考。
隨著學(xué)習(xí)不斷更新......
+++++++++++++++++++++++分割線總是要有的+++++++++++++++++++++++
首先到tp官網(wǎng)下載了一個最新的ThinkPHP5.0.22完整版:
直接扔到了服務(wù)器上,解壓后目錄結(jié)構(gòu)如下:
目錄結(jié)構(gòu)整體與tp3.2大同小異,文件夾首字母小寫了,應(yīng)用入口文件 在根目錄下 public/index.php,官方文檔對public文件夾定義為WEB部署目錄(對外訪問目錄):
配置服務(wù)器域名解析的時候需要把項目根目錄指向/public:
VirtualHost *:80> ServerAdmin 1977629361@qq.com DocumentRoot /var/www/tp/public ServerName tp.oyhdo.com ServerAlias tp.oyhdo.com DirectoryIndex index.php index.html index.htm /VirtualHost>
根目錄下 application/config.php 為應(yīng)用(公共)配置文件,設(shè)置一些常用的配置,以下簡稱為“配置文件”:
訪問網(wǎng)址如下:
訪問tp.oyhdo.com等同于訪問tp.oyhdo.com/index.php/index/Index/index(默認(rèn)不區(qū)分大小寫)
即默認(rèn)模塊index,默認(rèn)控制器Index,默認(rèn)操作index
配置文件修改分別為default_module、default_controller、default_action
如果需要強制區(qū)分url大小寫,修改 url_convert 為false
:
配置文件中設(shè)置 app_debug 為true
,打開應(yīng)用調(diào)試模式,以便開發(fā)調(diào)試:
【隱藏url中的index.php入口文件】
以Apache服務(wù)器為例,首先確認(rèn)Apache配置文件httpd.conf中開啟了mod_rewrite.so模塊:
然后把所有【AllowOverride】設(shè)為All:
最后修改根目錄下 public/.htaccess 文件內(nèi)容為:
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>
【隱藏前臺url模塊名】
把index模塊作為前臺,在前臺新建了一個User控制器:
?php namespace app\index\controller; class User { public function user() { return '這是User控制器的user操作'; } }
正常需要這樣訪問User控制器的user操作:
為了前臺url顯示簡潔一些,要去掉模塊名index,然后就崩了:
如果只有一個模塊,可以在 /application/common.php 中添加:
// 綁定當(dāng)前訪問到index模塊 define('BIND_MODULE','index');
親測訪問成功:
但是項目通常會有前后臺的區(qū)分,至少兩個模塊, 用上面的方法綁定index模塊后,再訪問其它模塊就會報錯:
(新建了一個admin模塊作為后臺)
?php namespace app\admin\controller; class Index { public function index() { return '這是后臺首頁'; } }
對于多模塊的情況,可以在 /application/route.php 中綁定默認(rèn)模塊路由(去掉上面的單模塊綁定):
use think\Route; Route::bind('index');
前臺訪問成功:
然后在/public/下新建一個入口文件admin.php,綁定后臺模塊admin,來訪問后臺:
?php // [ 應(yīng)用入口文件 ] namespace think; // 定義應(yīng)用目錄 define('APP_PATH', __DIR__ . '/../application/'); // 加載框架引導(dǎo)文件 require __DIR__ . '/../thinkphp/base.php'; // 綁定當(dāng)前入口文件到admin模塊 Route::bind('admin'); // 關(guān)閉admin模塊的路由 App::route(false); // 執(zhí)行應(yīng)用 App::run()->send();
后臺訪問成功:
(修改后臺地址只需修改這個文件名即可)
【返回數(shù)據(jù)】
配置文件中默認(rèn)輸出類型 default_return_type 為html:
直接打印輸出字符串、數(shù)組,沒什么特殊:
public function index() { $str = 'hello,world!'; $arr = array('state'=>1,'msg'=>'success'); //打印字符串 echo $str; //打印數(shù)組 var_dump($arr); }
返回json格式數(shù)據(jù):
public function index() { $arr = array('state'=>1,'msg'=>'success'); return json($arr); //返回其它狀態(tài)碼或響應(yīng)頭信息 //return json($arr, 201, ['Cache-control' => 'no-cache,must-revalidate']); //xml格式 //return xml($arr); }
(對于只做API開發(fā)的情況,可以設(shè)置default_return_type為json,直接return $arr
即可返回json格式數(shù)據(jù))
【渲染模板、分配數(shù)據(jù)】
如圖建立視圖層,index.html作為前臺首頁(內(nèi)容為“這是首頁”):
tp3渲染模板直接在控制器里$this->display()
,tp5并不支持。
tp5渲染模板,在控制器中繼承think\Controller類,使用 return $this->fetch()
或者使用助手函數(shù) return view()
:
?php namespace app\index\controller; use think\Controller; class Index extends Controller { public function index() { return $this->fetch(); //return view(); } }
tp5分配數(shù)據(jù)的方式依舊使用 $this->assign()
:
?php namespace app\index\controller; use think\Controller; class Index extends Controller { public function index() { $name = 'lws'; $this->assign('name',$name); return $this->fetch(); } }
index.html頁面讀取數(shù)據(jù):
{$name}
(修改模板引擎標(biāo)簽 配置文件【tpl_begin】、【tpl_end】)
【繼承父類控制器】
寫一個栗子,新建一個Base控制器作為父類控制器,Index控制器繼承Base控制器
在父類控制器中初始化分配數(shù)據(jù),子類控制器渲染模板:
Base.php:
?php namespace app\index\controller; use think\Controller; class Base extends Controller { //初始化方法 public function _initialize() { $haha = '快下班了'; $this->assign('haha',$haha); } }
Index.php:
?php namespace app\index\controller; use think\Controller; class Index extends Base { public function index() { return $this->fetch(); } }
index.html:
{$haha}
(與tp3.2相比,父類控制器不能是Public控制器)
【配置參數(shù)】
tp3.2里面使用C方法設(shè)置、獲取配置參數(shù)
tp5使用助手函數(shù) config()
設(shè)置、獲取配置參數(shù):
//配置一個參數(shù) config('name','lws'); //批量配置參數(shù) config([ 'info'=>['sex'=>'nan','aihao'=>'nv'] ]); //獲取一個配置參數(shù) echo config('name'); //獲取一組配置參數(shù) dump(config('info')); //獲取一個二級配置參數(shù) echo config('info.sex');
【get傳參】
tp5廢除了url/參數(shù)名1/參數(shù)值1/參數(shù)名2/參數(shù)值2......這樣的方式傳參,還是老老實實用url?參數(shù)名1=參數(shù)值1參數(shù)名2=參數(shù)值2......這樣傳吧。
控制器里打印$_GET
:
?php namespace app\index\controller; use think\Controller; class Index extends Controller { public function index() { $getdate = $_GET; dump($getdate); } }
這樣是不對滴:
這樣就好使:
【安全獲取變量】
tp3.2可以使用I方法安全獲取get、post等系統(tǒng)輸入變量
tp5中使用助手函數(shù) input()
//獲取get變量 $data1 = input('get.name'); //獲取post變量 $data2 = input('post.name'); //獲取當(dāng)前請求變量 $data3 = input('param.name'); //獲取request變量 $data4 = input('request.name'); //獲取cookie變量 $data5 = input('cookie.name'); //獲取session變量 $data6 = input('session.name'); //獲取上傳文件信息 $data7 = input('file.image');
(注意:獲取的數(shù)據(jù)為數(shù)組,要加上 /a 修飾符才能獲取到)
$arr = input('post.arr/a');
可以在配置文件中設(shè)置全局過濾方法:
// 默認(rèn)全局過濾方法 用逗號分隔多個 'default_filter' => 'htmlspecialchars',
【數(shù)據(jù)庫操作】
tp5的數(shù)據(jù)庫配置文件在根目錄 /application/database.php:(也可在模塊下單獨配置)
連接數(shù)據(jù)庫:tp3.2支持M方法連接數(shù)據(jù)庫,tp5使用 Db類 或 助手函數(shù)db()
查詢數(shù)據(jù):依舊使用 find()
、select()
方法,查詢一個字段使用 value()
方法代替getField()
//查詢一條 $artinfo = db('article')->find(); //查詢?nèi)? $artinfo = db('article')->select(); //查詢一個字段 $artinfo = db('article')->value('article_title');
添加數(shù)據(jù):tp3.2使用add()
,tp5使用 insert()
:返回插入條數(shù) 或 save()
:返回id
//添加一條數(shù)據(jù) $data['article_title'] = 'PHP是世界上最好的語言'; $data['article_content'] = '如題'; db('article')->insert($data); //或 db('article')->save($data);
//添加多條數(shù)據(jù) $data = [ ['article_title' => '標(biāo)題1', 'article_content' => '內(nèi)容1'], ['article_title' => '標(biāo)題2', 'article_content' => '內(nèi)容2'], ['article_title' => '標(biāo)題3', 'article_content' => '內(nèi)容3'] ]; db('article')->insertAll($data);
修改數(shù)據(jù):tp3.2使用save()
,tp5使用 update()
//修改數(shù)據(jù) $whe['article_id'] = 1; $data['article_title'] = '修改后的標(biāo)題'; db('article')->where($whe)->update($data);
刪除數(shù)據(jù):沒錯還是 delete()
//刪除數(shù)據(jù) $whe['article_id'] = 1; db('article')->where($whe)->delete();
db()
助手使用起來比較方便,但每次都會重新連接數(shù)據(jù)庫,因此應(yīng)當(dāng)盡量避免多次調(diào)用,建議還是使用Db類操作數(shù)據(jù)庫。
Db類操作原生SQL:
?php namespace app\index\controller; use think\Db; class Index { public function index() { // 插入記錄 $res = Db::execute('insert into lws_article (title ,content) values ("標(biāo)題", "內(nèi)容")'); // 刪除數(shù)據(jù) $res = Db::execute('delete from lws_article where art_id = 1 '); // 更新記錄 $res = Db::execute('update lws_article set title = "修改標(biāo)題" where art_id = 1 '); // 查詢數(shù)據(jù) $res = Db::query('select * from lws_article where art_id = 1'); // 顯示數(shù)據(jù)庫列表 $res = Db::query('show tables from blog'); // 清空數(shù)據(jù)表 $res = Db::execute('TRUNCATE table lws_article'); } }
Db類操作查詢構(gòu)造器:
?php namespace app\index\controller; use think\Db; class Index { public function index() { // 查詢數(shù)據(jù)(數(shù)據(jù)庫沒有配置表前綴) $res = Db::table('lws_article') ->where('art_id', 1) ->select(); //以下為數(shù)據(jù)庫配置了表前綴 // 插入記錄 $res = Db::name('article') ->insert(['title' => '標(biāo)題', 'content' => '內(nèi)容']); // 更新記錄 $res = Db::name('article') ->where('art_id', 1) ->update(['title' => "修改標(biāo)題"]); // 查詢數(shù)據(jù) $res = Db::name('article') ->where('art_id', 1) ->select(); // 刪除數(shù)據(jù) $res = Db::name('article') ->where('art_id', 1) ->delete(); //鏈?zhǔn)讲僮髋e例 $artlist = Db::name('article') ->where('is_del', 'N') ->field('id,title,content') ->order('post_time', 'desc') ->limit(10) ->select(); } }
【切換數(shù)據(jù)庫】
首先在數(shù)據(jù)庫配置中配置多個數(shù)據(jù)庫:
// 數(shù)據(jù)庫配置1 'db1' => [ // 數(shù)據(jù)庫類型 'type' => 'mysql', // 服務(wù)器地址 'hostname' => '127.0.0.1', // 數(shù)據(jù)庫名 'database' => 'blog1', // 數(shù)據(jù)庫用戶名 'username' => 'root', // 數(shù)據(jù)庫密碼 'password' => '123456', // 數(shù)據(jù)庫連接端口 'hostport' => '', // 數(shù)據(jù)庫連接參數(shù) 'params' => [], // 數(shù)據(jù)庫編碼默認(rèn)采用utf8 'charset' => 'utf8', // 數(shù)據(jù)庫表前綴 'prefix' => 'lws_', ], // 數(shù)據(jù)庫配置2 'db2' => [ // 數(shù)據(jù)庫類型 'type' => 'mysql', // 服務(wù)器地址 'hostname' => '127.0.0.1', // 數(shù)據(jù)庫名 'database' => 'blog2', // 數(shù)據(jù)庫用戶名 'username' => 'root', // 數(shù)據(jù)庫密碼 'password' => '', // 數(shù)據(jù)庫連接端口 'hostport' => '', // 數(shù)據(jù)庫連接參數(shù) 'params' => [], // 數(shù)據(jù)庫編碼默認(rèn)采用utf8 'charset' => 'utf8', // 數(shù)據(jù)庫表前綴 'prefix' => 'lws_', ],
使用connect方法切換數(shù)據(jù)庫:
?php namespace app\index\controller; use think\Db; class Index { public function index() { $db1 = Db::connect('db1'); $db2 = Db::connect('db2'); $db1->query('select * from lws_article where art_id = 1'); $db2->query('select * from lws_article where art_id = 2'); } }
【系統(tǒng)常量】
tp5廢除了一大堆常量:
REQUEST_METHOD IS_GET IS_POST IS_PUT IS_DELETE IS_AJAX __EXT__ COMMON_MODULE MODULE_NAME CONTROLLER_NAME ACTION_NAME APP_NAMESPACE APP_DEBUG MODULE_PATH等
需要使用的常量可以自己定義,例如IS_GET、IS_POST
我在父類的初始化方法中定義了這兩個常量:
?php namespace app\index\controller; use think\Controller; class Base extends Controller { public function _initialize() { define('IS_GET',request()->isGet()); define('IS_POST',request()->isPost()); } }
然后在子類控制器中就可以使用這個常量做一些判斷:
?php namespace app\index\controller; class Index extends Base { public function index() { if(IS_POST){ echo 111; }else{ echo 222; } } }
【定義路由】
例如一篇博客詳情頁,原來的網(wǎng)址為:http://oyhdo.com/home/article/detial?id=50,即home模塊下的article控制器下的detial操作方法,傳遞參數(shù)id。
在路由配置文件 application/route.php 中添加路由規(guī)則:
return [ 'article/:id' => 'home/article/detial', ];
或者使用 Route 類,效果一樣:
use think\Route; Route::rule('article/:id','home/article/detial');
定義路由規(guī)則之后訪問http://oyhdo.com/article/50即可
【url分隔符的修改】
修改 application/config.php 中的 pathinfo_depr :
// pathinfo分隔符 'pathinfo_depr' => '-',
訪問網(wǎng)址變?yōu)椋?span style="color: #0000ff">http://oyhdo.com/article-50
【跳轉(zhuǎn)、重定向】
tp3里面的正確跳轉(zhuǎn):$this->success()
、錯誤跳轉(zhuǎn):$this->error()
、重定向:$this->redirect()
,在tp5里面同樣適用(繼承\think\Controller)
tp5新增 redirect()
助手函數(shù)用于重定向:
return redirect('https://www.oyhdo.com');
更多關(guān)于thinkPHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《ThinkPHP入門教程》、《thinkPHP模板操作技巧總結(jié)》、《ThinkPHP常用方法總結(jié)》、《codeigniter入門教程》、《CI(CodeIgniter)框架進階教程》、《Zend FrameWork框架入門教程》及《PHP模板技術(shù)總結(jié)》。
希望本文所述對大家基于ThinkPHP框架的PHP程序設(shè)計有所幫助。
標(biāo)簽:涼山 九江 甘肅 昭通 韶關(guān) 十堰 遼陽 梅河口
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《從ThinkPHP3.2.3過渡到ThinkPHP5.0學(xué)習(xí)筆記圖文詳解》,本文關(guān)鍵詞 從,ThinkPHP3.2.3,過渡到,ThinkPHP5.0,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。