一 : ThinkPHP配置前準備:
配置前需要安裝PHP5.4.0以上版本
ThinkPHP5.0完全開發手冊
1 : 對于Mac系統
Mac上安裝配置Apache +Tomcat+JDK
2 : linux 或者 CentOS 等
php7詳細安裝教程(linux + nginx +PHP + mysql)
Linux 安裝和卸載 nginx操作
3 : 下面以本地電腦為例:
打開: http://localhost 顯示 it works ! 說明Apache配置ok,
復制一個info.php文件到根目錄下,http://localhost/info.php顯示PHP相關信息說明php環境ok.
在上面步驟3條件下,繼續往下
二 : ThinkPHP文件下載
下載方式一:
(1) : 官網 http://www.thinkphp.cn/
注冊登錄官網,直接下載:
(2) : 找到你的Apache的web根目錄,
比如我的是
/Library/WebServer/Documents/
將下載的文件直接解壓到該路徑下:
(3) : 打開連接: http://localhost/public/
(注意: 如果你的項目不是在根路徑下,比如在創建項目/thinkPHPPro/下
那么路徑應該是http://你的域名/thinkPHPPro/public)
顯示如下,說明基礎環境ok:
如果不成功,給runtime文件設置一下權限:
chmod -R 777 /Library/WebServer/Documents/runtime
下載方式二 : 通過git 下載(4行語句) git安裝文檔
cd /Library/WebServer/Documents/
git init
git clone https://git.coding.net/liu21st/thinkphp5.git
git clone https://git.coding.net/liu21st/framework.git
(將thinkphp5移動到framework文件夾下)
簡單下載示例(可忽視):
-bash: php-version: command not found
localhost:niexiaobo niexiaobo$ cd /Users/niexiaobo/Downloads/php5
localhost:php5 niexiaobo$ git init
Initialized empty Git repository in /Users/niexiaobo/Downloads/php5/.git/
localhost:php5 niexiaobo$ git clone https://git.coding.net/liu21st/thinkphp5.git
Cloning into 'thinkphp5'...
remote: Counting objects: 13519, done.
remote: Compressing objects: 100% (19/19), done.
remote: Total 13519 (delta 10), reused 0 (delta 0)
Receiving objects: 100% (13519/13519), 5.76 MiB | 3.20 MiB/s, done.
Resolving deltas: 100% (8588/8588), done.
localhost:php5 niexiaobo$ git clone https://git.coding.net/liu21st/framework.git
Cloning into 'framework'...
remote: Counting objects: 43528, done.
remote: Compressing objects: 100% (16100/16100), done.
remote: Total 43528 (delta 26953), reused 42770 (delta 26499)
Receiving objects: 100% (43528/43528), 10.67 MiB | 2.88 MiB/s, done.
Resolving deltas: 100% (26953/26953), done.
localhost:php5 niexiaobo$
三 : ThinkPHP文件目錄結構
ThinkPHP 5相對于以往3的版本做了一些改變:
project 應用部署目錄
├─application 應用目錄(可設置)
│ ├─common 公共模塊目錄(可更改)
│ ├─index 模塊目錄(可更改)
│ │ ├─config.php 模塊配置文件
│ │ ├─common.php 模塊函數文件
│ │ ├─controller 控制器目錄
│ │ ├─model 模型目錄
│ │ ├─view 視圖目錄
│ │ └─ ... 更多類庫目錄
│ ├─command.php 命令行工具配置文件
│ ├─common.php 應用公共(函數)文件
│ ├─config.php 應用(公共)配置文件
│ ├─database.php 數據庫配置文件
│ ├─tags.php 應用行為擴展定義文件
│ └─route.php 路由配置文件
├─extend 擴展類庫目錄(可定義)
├─public WEB 部署目錄(對外訪問目錄)
│ ├─static 靜態資源存放目錄(css,js,image)
│ ├─index.php 應用入口文件
│ ├─router.php 快速測試文件
│ └─.htaccess 用于 apache 的重寫
├─runtime 應用的運行時目錄(可寫,可設置)
├─vendor 第三方類庫目錄(Composer)
├─thinkphp 框架系統目錄
│ ├─lang 語言包目錄
│ ├─library 框架核心類庫目錄
│ │ ├─think Think 類庫包目錄
│ │ └─traits 系統 Traits 目錄
│ ├─tpl 系統模板目錄
│ ├─.htaccess 用于 apache 的重寫
│ ├─.travis.yml CI 定義文件
│ ├─base.php 基礎定義文件
│ ├─composer.json composer 定義文件
│ ├─console.php 控制臺入口文件
│ ├─convention.php 慣例配置文件
│ ├─helper.php 助手函數文件(可選)
│ ├─LICENSE.txt 授權說明文件
│ ├─phpunit.xml 單元測試配置文件
│ ├─README.md README 文件
│ └─start.php 框架引導文件
├─build.php 自動生成定義文件(參考)
├─composer.json composer 定義文件
├─LICENSE.txt 授權說明文件
├─README.md README 文件
├─think 命令行入口文件
四 : ThinkPHP簡單使用
(1) : 修改默認頁面
上文中有介紹,打開連接: http://localhost/public/顯示一段默認頁面.
那么該頁面具體位置在哪呢?
對默認項目的
application/index/controller/index.php
做一些簡單的修改:
默認代碼:
<?php
namespace app\index\controller;
class Index
{
public function index()
{
return '<style type="text/css">*{ padding: 0; margin: 0; } .think_default_text{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p> ThinkPHP V5<br/><span style="font-size:30px">十年磨一劍 - 為API開發設計的高性能框架</span></p><span style="font-size:22px;">[ V5.0 版本由 <a target="qiniu">七牛云</a> 獨家贊助發布 ]</span></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="ad_bd568ce7058a1091"></think>';
}
}
修改后:
<?php
namespace app\index\controller;
class Index
{
public function index()
{
return 'Hello,World! this is default page !';
}
}
保存后http://localhost/public鏈接顯示的就是 'Hello,World! this is default page !'這句話了.
(2) : 模板渲染
修改項目的application/index/controller/index.php
文件:
主要修改有:引用Controller類 , 擴展index類方法 , 添加方法hello.
修改后如下:
<?php
namespace app\index\controller;
use think\Controller;//引入Controller類
class Index extends Controller
{
public function index()
{
return 'Hello,World! this is default page !';
}
public function hello()
{
return 'hello';
}
}
打開http://localhost/public/index.php/index/index/hello鏈接
顯示如下:
上述只是通過修改模板,無需創建相應文件就可以返回.
(3) : 模板渲染, 并創建文件
還是修改項目的application/index/controller/index.php
文件:
index方法,結果如下:
<?php
namespace app\index\controller;
use think\Controller;//引入Controller類
class Index extends Controller
{
public function index($name='聶小波')
{
$this->assign('name',$name);
return $this->fetch();
}
public function hello()
{
return 'hello';
}
}
修改后index需要獲取變量的,此時打開http://localhost/public鏈接會報錯的,因為還沒有index.html文件.
進入項目的application/index/下創建view文件夾,再進入view下創建index文件夾進入再創建index.html.(如下圖所示)
編輯index.html:
<html>
<head>
<title>hello {$name}</title>
</head>
<body>
hello {$name}!
</body>
</html>
打開地址http://localhost/public/index.php/index/index顯示:
index.html展示時需要一個name變量值,而該值是通過index.php中模板方法傳遞過來的.
(5) : 通過參數param獲取內容
修改上面index.php中的hello方法:
public function hello(Request $request)
{
echo 'hello :'.$request->param('name').'!';
echo '你今年'.$request->param('age').'歲 !';
}
打開鏈接地址:
http://localhost/public/index.php/index/index/hello.html?name=bobo&age=18
參數有姓名和年齡,結果如圖:
(4) : 鏈接數據庫mysql
還是修改項目的application/index/controller/index.php
文件:
準備工作:
安裝mysql,創建數據庫testDB,創建表testTable,表里面添加幾條數據,包含字段id, uname,等等
添加dbTest方法(域名localhost不行的話要用127.0.0.1),
use think\Db;//引入數據庫
結果如下:
<?php
namespace app\index\controller;
use think\Controller;//引入Controller類
use think\Db;//引入數據庫
class Index extends Controller
{
public function index($name='聶小波')
{
$this->assign('name',$name);
return $this->fetch();
}
public function hello()
{
return 'hello';
}
public function dbTest()
{
return Db::connect([
'type'=>'mysql',
'hostname'=>'127.0.0.1',
'database'=>'testDB',
'username'=>'root',
'password'=>'root',
])
->table('testTable')
->where('id','2')
->value('uname');
}
}
dbTest(): 查詢testTable表中id=2 的uname字段:
打開鏈接http://localhost/public/index.php/index/index/dbtest
結果如下:
(6) : 統一配置數據庫mysql信息
在上面dbTest(): 中我們需要設置登錄信息, 下面開始在公共文件統一配置:
進入項目文件編輯: /application/database.php
return [
// 數據庫類型
'type' => 'mysql',
// 服務器地址
'hostname' => '127.0.0.1',
// 數據庫名
'database' => 'testA',
// 用戶名
'username' => 'root',
// 密碼
'password' => 'root',
// 端口
'hostport' => '3306',
// 連接dsn
'dsn' => '',
// 數據庫連接參數
'params' => [],
// 數據庫編碼默認采用utf8
'charset' => 'utf8',
// 數據庫表前綴
.
.
.
還是修改項目的application/index/controller/index.php
文件:
添加dbTest2方法(查詢testTable表下id=2的整條數據):
public function dbTest2()
{
$res = Db::table('testTable')->where('id',2)->find();
dump(is_null($res)?'沒有查到':$res);
}
打開連接http://localhost/public/index.php/index/index/dbTest2
結果如下,返回成功,以后就不需要重復設置登錄信息了:
更多數據庫操作方法: ThinkPHP5.0完全開發手冊
(https://www.cnblogs.com/samphp/p/8594291.html)
//1、單條查詢
public function dbTest4()
{
$res = Db::table('pzq_article')
->field(['title'=>'標題','id'=>'編號'])//可添加別名
->where('id','=',20)//如果是等號,=可以省略
->find();//如果是主鍵查詢,可省略上面where,這行寫->find(20);
dump(is_null($res)?'沒有查到':$res);
}
//2、多條查旬
public function dbTest5()
{
$res = Db::table('pzq_article')
->field(['id','cat_id','title'])
->where([
['id','>',20],
['cat_id','=',2],
])//一個條件,直接用表達式->where('id','>',20)。多個條件用數組
->order('id desc')->limit(3)->select();
if(empty($res)){
return '沒有查到';
}else{
dump($res);
}
}
//3、數據添加
public function dbTest6()
{
$data = [
'name'=>'Sam2',
'age'=>'29',
'posttime'=>time()
];
$dataall=[
['name'=>'Sam3','age'=>'29','posttime'=>time()],
['name'=>'Sam4','age'=>'30','posttime'=>time()],
];
//(1)單條插入
//return Db::table('test')->data($data)->insert();
//(2)插入同時返回新增主鍵id
//return Db::table('test')->insertGetId($data);
//(3)插入多條數據
return Db::table('test')->data($dataall)->insertAll();
}
//4更新數據
public function dbTest7()
{
// return Db::table('test')
// ->where('id','=',4)
// ->update(['name'=>'SamC','age'=>'31']);
//如果where條件是主鍵,還可以如下使用
return Db::table('test')
->update(['name'=>'SamCheng','age'=>'30','id'=>4]);
}
//5刪除操作
public function dbTest8()
{
//return Db::table('test')->delete(6);
//或者
return Db::table('test')->where('id',5)->delete();
}
//mysql原生語句 查詢
public function dbTest9()
{
$sql = "select name,age from test where id>2";
dump(Db::query($sql));
}
//mysql 增、刪、改 用Db::execute($sql)
public function dbTest10()
{
//$sql = "update test set name='samC' where id=4";
//$sql = "insert test set name='Yan',age='30'";
$sql = "delete from test where id=4";
return Db::execute($sql);
}
五 : ThinkPHP路由設置
(7) : 路由: 隱藏真實路徑
修改項目路徑下 /application/route.php
修改前初始代碼:
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
return [
'__pattern__' => [
'name' => '\w+',
],
'[hello]' => [
':id' => ['index/hello', ['method' => 'get'], ['id' => '\d+']],
':name' => ['index/hello', ['method' => 'post']],
],
];
添加一段代碼:
<?php
return [
'__pattern__' => [
'name' => '\w+',
],
'[hello]' => [
':id' => ['index/hello', ['method' => 'get'], ['id' => '\d+']],
':name' => ['index/hello', ['method' => 'post']],
],
'__alias__' => [
'home' => 'index/index',
],
];
或者這樣寫:
<?php
use think\Route;
Route::alias('home','index/index');
意思是真實路徑里的index/index都可以使用home來代替:
比如:步驟(6)中打開連接http://localhost/public/index.php/index/index/dbTest2
和
打開連接http://localhost/public/index.php/home/dbTest2
效果是一樣的.
更多路由設置參考 ThinkPHP5.1完全開發手冊
(8) : 路由: 頁面跳轉
下面以登錄為例,登錄成功后跳轉到首頁index,失敗后跳轉錯誤頁面
還是修改項目的application/index/controller/index.php
文件:
添加login方法和check()方法:
// 顯示登錄頁面
public function login(){
return $this->fetch();
}
//提交登錄
public function check(){
//獲取參數
$user=$_POST['username'];
$pwd=$_POST['password'];
// 判斷登陸成功失敗的邏輯
if($user=='admin' && $pwd=='123'){
//如果成功則跳到index/index頁面
$this->success('登陸成功',url('/index/index'));
}else{
$this->error('登陸失敗');
}
}
下面路徑下創建login.html登錄驗證頁面:
/application/index/view/index/login.html
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陸</title>
</head>
<body>
<!--{:url('check')} :提交到本頁面的控制器下的check方法-->
<form action="{:url('check')}" method="post">
<p>
賬號:<input type="text" name="username" id="username">
</p>
<P>
密碼:<input type="text" name="password" id="password">
</P>
<p>
<input type="submit" value="提交">
<input type="reset" value="重置">
</p>
</form>
</body>
</html>
打開下面地址
http://localhost/public/index.php/index/index/login.html
輸入錯誤的username,點擊提交按鈕:
登錄失敗, 跳轉錯誤頁面(默認3秒倒計時):
輸入正確賬號密碼admin 和 123.
跳轉成功頁面(默認3秒倒計時),然后回到index頁面:
(9) : 路由: 頁面重定向
打開某個鏈接時,直接跳轉到其他地址
還是修改項目的application/index/controller/index.php
文件:
添加跳轉方法:
// 頁面重定向
public function jumpto(){
$this->redirect('https://www.baidu.com');
}
打開鏈接:
http://localhost/public/index.php/index/index/jumpto
成功跳轉到百度頁面:
(10-A) : 模型的使用 : 查詢表
目的 : 通過創建使用Model來查詢表數據
1 : 首先數據庫有一張表chat.
2 : 在/application/index/下新建model文件夾,并創建一個Chat.php文件(根據表名, 駝峰命名,首字母大寫)
Chat.php :
<?php
namespace app\index\model;
use think\Model;
class Chat extends Model{
// 設置當前模型對應的完整數據表名稱
protected $table="chat";
}
?>
3 : 還是修改項目的application/index/controller/index.php文件:
添加跳轉方法:
//模型
public function user()
{
// 實例化數據模型
$user=new \app\index\model\Chat;
//get(3): 查詢主鍵為3的數據,并轉成array返回
dump($user::get(3)->toArray());
}
4 : 打開連接:http://localhost/public/index.php/home/user
也即是http://localhost/public/index.php/index/index/user
(10-B) : 模型的理解
通過上述對模型的簡單使用之后,接著對模型做一個簡單是介紹:
1 這里的模型model到底是什么?
根據使用方法:
use think\Model;
class Chat extends Model
知道: 我們新建的Chat模型文件,其實是繼承了think\Model文件的功能和方法,說明Chat模型在創建初始化結束后,就擁有了think下Model的功能.
修改上述控制器方法
//模型
public function user()
{
// 實例化數據模型
$user=new \app\index\model\Chat;
//直接打印模型
dump($user);
}
打開鏈接http://localhost/public/index.php/index/index/user
結果如下:
object(app\index\model\Chat)#10 (35) {
["table":protected] => string(10) "think_user"
["connection":protected] => array(0) {
}
["parent":protected] => NULL
["query":protected] => NULL
["name":protected] => string(4) "Chat"
["class":protected] => string(20) "app\index\model\Chat"
["error":protected] => NULL
["validate":protected] => NULL
["pk":protected] => NULL
["field":protected] => array(0) {
}
["except":protected] => array(0) {
}
["disuse":protected] => array(0) {
}
["readonly":protected] => array(0) {
}
["visible":protected] => array(0) {
}
["hidden":protected] => array(0) {
}
["append":protected] => array(0) {
}
["data":protected] => array(0) {
}
["origin":protected] => array(0) {
}
["relation":protected] => array(0) {
}
["auto":protected] => array(0) {
}
["insert":protected] => array(0) {
}
["update":protected] => array(0) {
}
["autoWriteTimestamp":protected] => bool(false)
["createTime":protected] => string(11) "create_time"
["updateTime":protected] => string(11) "update_time"
["dateFormat":protected] => string(11) "Y-m-d H:i:s"
["type":protected] => array(0) {
}
["isUpdate":protected] => bool(false)
["force":protected] => bool(false)
["updateWhere":protected] => NULL
["failException":protected] => bool(false)
["useGlobalScope":protected] => bool(true)
["batchValidate":protected] => bool(false)
["resultSetType":protected] => string(5) "array"
["relationWrite":protected] => NULL
}
返回的一堆信息中:
第一條:
["table":protected] => string(10) "think_user"
意思是該模型設置的需要修改的表是think_user.
中間某條:
["append":protected]
意思是具有追加數據的功能
中間某條:
["data":protected]
專門存儲數據的
比如下面操作修改的就是這個data:
$user = new User;
$user->data([
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com'
]);
所以,模型文件能夠更好的幫我們處理一些數據庫相關的操作邏輯
(11) : 控制器 : 創建新的控制器
目前為止都是在項目的application/index/controller/index.php修改,這個默認控制器文件index.php .
創建文件login.php:
application/index/controller/login.php
寫法和index.php一樣:
<?php
namespace app\index\controller;
class login
{
public function index()
{
return 'login !';
}
public function hello()
{
return 'hello';
}
}
打開地址:
http://localhost/public/index.php/index/login
http://localhost/public/index.php/index/login/hello
(11) : 后臺目錄文件
同默認控制器,在 application/下創建admin文件,專門用來存放和管理后臺頁面代碼(開發方式和上文基本一致):
控制器:
application/admin/controller/index.php
前端html入口(view下存放):
application/admin/view/index.html
前端html 的CSS,js,image等靜態文件存儲路徑:
/public/static/
前端html 的CSS,js,image靜態文件生效設置:
編輯/application/config.php:
// 視圖輸出字符串內容替換
'view_replace_str' => [
'__PUBLIC__'=>'/public/static', //將__PUBLIC__指向public/static
'__ROOT__' => '/',
],
引用/public/static下home/css文件:
<link rel="stylesheet" type="text/css" href="__PUBLIC__/home/css/demo.css">
經過上述配置后,訪問http://localhost/public/index.php/admin/ 就可以進入后臺管理界面.