ThinkPHP5.0學習筆記

ThinkPHP 5.0 學習筆記

設置使用域名訪問本機

打開c:\Windows\System32\drivers\etc\host文件

添加

127.0.0.1  www.tp5.com

修改完成之後,保存

使用cmd命令行去ping該域名

[外鏈圖片轉存失敗(img-KeaaQHkd-1568536528011)(C:\Users\王龍\Desktop\批註 2019-08-10 124500.jpg)]

若ping得本機則成功。

修改服務器配置,使鍵入域名時跳轉到指定文件目錄下

服務器使用apache時,修改Httpd.conf

添加內容

<VirtualHost *:80>
	DocumentRoot "C:\wamp\www\tp5\public"
	ServerName www.tp5.com
</VirtualHost>

即可以使用www.tp5.com域名直接進入C:\wamp\www\tp5\public文件目錄下

文件目錄

application:應用目錄
extend :拓展類庫
public :入口文件
runtime :運行緩存文件
thinkphp :框架核心文件
vendor :第三方類庫

TP5.0\application\config.php 項目配置文件
開發環境開啓debug模式
TP5.0\application\database.php 數據庫配置文件

使用$this->request安全對象來獲取內容,request->param() 用來代替_GET_,POST

模塊/控制器/方法

URL和路由

控制器名首字母大寫
加’_'之後,解析url時去掉‘_’,並且將緊鄰字母轉換爲大寫
路由

路由註冊

動態註冊

Route::rule(‘路由表達式’,‘路由地址’,‘請求類型’,‘路由參數(數組)’,‘變量規則(數組)’);

use think\Route;
return [
    Route::rule('hello/[:name]','index/index/hello'),
    ...
];

//或
    
return [
    'hello/[:name]' => ['index/index/index2',['methon' => 'get']],
    ...
];

當訪問http://localhost/hello/name時,會自動路由到http://localhost/index/index/hello/name

未添加動態路由時

在這裏插入圖片描述

添加內容如下

'index2/[:name]' => ['index/index/index2',['method' => 'get']],

添加動態路由後

在這裏插入圖片描述

多值傳輸

	public function today($year = 1970 ,$mouth = 1,$day = 1)
	{
		echo "今天是".$year."年".$mouth."月".$day."日";
	}

在這裏插入圖片描述

添加動態路由,並限制傳輸年份爲4個數字,月份爲2個數字

'today/[:year]/[:mouth]/[:day]' => ['index/index/today',['method' => 'get'],['year' => '\d{4}','mouth' => '\d{2}']],

在這裏插入圖片描述

自動生成url

	public function url1()
	{
		echo url('index2','name=aaa');
        //內置url函數,第一個參數若不全時一般默認爲當前模塊下當前控制器下的index2方法,並且傳值名爲name,值爲aaa,
	}

效果:

在這裏插入圖片描述

Request對象使用

use think\Request;	
public function myRequest($name = 'hello')
	{
	    echo $name."<br>";
	    echo "request參數<br>";
	    $request = Request::instance();		//初始化request對象
	    print_r( $request -> param());		//使用request對象的param()方法查詢傳遞參數
	    echo "<br>";
	    print_r( $request -> cookie());		//查詢cookie值
	    echo "<br>";
	    echo $request -> param('name');
	    //$request 屬性綁定
	    $request->bind('user','wl');
	}

查詢結果

在這裏插入圖片描述

response

	public function myResponse()
	{
	    //$data = ['name' => 'wl','status' => '1'];
	    //return $data;    //格式不正確
	    //return json($data);    //屏幕打印json格式的data
	    //return json($data,201);//屏幕打印json格式的data,並修改status
	    //return xml($data);     //屏幕打印xml格式的data
	    
	   $this->assign('name','wl');
	   return $this->fetch('index');  //跳轉到對應index方法view模板文件,並傳值
	    
	    //$this->success("成功跳轉",'myRequest');  //延時成功跳轉
	    //$this->error("失敗跳轉","index2");       //延時失敗跳轉
	    //$this->redirect("http://www.baidu.com");//直接跳轉
	}

數據庫基本操作


user think\Db
$result = Db::connect('databaseName')->query('SQLs');
/*databaseName需提前在database.php中配置,SQLs爲sql語句,*/

$db = Db::connect('db');
$db->query('SQLs')

數據庫事務、鏈式操作

查詢構造器

use think\Db;
Db::table('type_tableName')
	->insert(['id' => 6,'name' => 'think','status' => '1']);	//插入
	
Db::table('type_tableName')
	->where('id',2)
	->update(['name' => "hello"]);	//更新
	
Db::table('type_tableName')
	->where('id',2)
	->select();	//查找
	
Db::table('type_tableName')
	->where('id',2)
	->delete();	//刪除
/*比較麻煩,當修改了database.php中的前綴時,需逐一修改SQL語句*/


Db::name('tableName')
	->insert(['id' => 6,'name' => 'think','status' => '1'])	//插入
/*當執行插入時,會在database.php中自動搜索前綴名加上,這樣就不需要多處修改,較爲簡潔*/
    
//更新數據庫數據時,若使用了關聯數組進行更新,則關聯數組中必須含有主鍵,或語句中有where語句,例如
$data = [
    'id' => input('id'),
    'title' => input('articletitle'),
    'descr' =>input('articledescr'),
    'keywords' => input('articlekeyword'),
    'content' =>input('articlecontent'),
    'author' => input('articleauthor'),
    'time' => time(),
    'cateid' => input('articlecateid'),
];
$save = db('article')->update($data);
//id 爲主鍵,若無主鍵,則會報 缺少更新條件 錯誤

鏈式操作

use think\Db;
Db::table('type_tableName')
	->where('status',1)		//status爲1
	->order('create_time')	//按create_time排序
	->limit(10)				//十條記錄
	->select();
	/*這裏的where、order、limit就被稱爲鏈式操作方法,除了select必須放在最後,其他沒有先後順序之分*/

Db::table("tp_article")
    ->alias('a')
    ->join('tp_cate c','a.cateid=c.id')
    ->field('a.id,a.cateid,a.title,c.catename')
    ->select();
//意爲在tp_article和tp_cate表裏進行聯合查找,查找articel.cateid=cate.id的a.id,a.cateid,a.title,c.catename屬性內容

更多相關信息,參考點擊鏈接

事務

一系列基礎操作,要麼全部成功,要麼全部失敗
將mysql的存儲引擎設爲InnoDB

使用transaction方法操作數據庫事務,當發生異常時會自動回滾

//自動控制事務處理
use think\Db;
Db::transaction(function(){
    	Db::table('type_tableName')->find(1);
    	Db::table('type_tableName')->delete(1);
});


//手動控制事務
Db::startTrans();	//啓動事務
try{
    Db::table('type_tableName')->find(1);
    Db::table('type_tableName')->delete(1);
    Db::commit();	//提交事務
}catch(\Exception $e){
    Db::rollback();	//回滾事務
}





模板輸出

//模板輸出,需要在相應控制器的方法中聲明,若聲明不正確或未聲明,報未定義error

//控制器,變量
$admin = 'hello';
//模板,輸出變量
{$admin}

//控制器,數組
$admin = [
    'name' => 'wl',
    'age' => '20',
    'sex' => 'man',
];
$this->assign('admin',$admin)
//模板,輸出數組元素
{$admin['name']}

//控制器,類
$admin = new Admin();
//模板,輸出類內元素
{$admin:age}
{$admin->name}


//當使用比較標籤時,可以如下操作,意爲當$a.value等於1時,輸出keyvalue
{compare name="$a.value" value="1" type="eq"}keyvalue{/compare}

使用驗證器


/*
C:\wamp\www\tp5\application\admin\validate
該目錄下爲驗證期目錄,新建名稱與控制器相同的驗證器文件
*/
<?php
namespace app\admin\validate;

use think\Validate;

class Cate extends Validate
{
    protected $rule = [
        'catename|欄目名稱' => 'require|max:30|unique:cate',
    ];
    //驗證期規則
    
    protected $message = [
        'cate.require' => '欄目名稱不能爲空',
        'cate.max' => '欄目名稱長度不能大於30個字符',
        'cate.unique' => '欄目名稱已經存在',
    ];
    //驗證期相應提示信息
    
    protected $scene = [
        'edit' => ['catename'],
        'add' => ['catename'],
    ];
}

?>

    
/*
C:\wamp\www\tp5\application\admin\controller
該文件夾下爲控制器文件
調用驗證器代碼如下
*/
$data = [
  catename = input('catename'),
];
$validate = \think\Loader::validate('Cate');	//實例化驗證器類
if($validate->scene('edit')->check($data) === false)	//注意使用全等===來進行判斷,否則某些驗證規則無法生效,如unique等
{
    $this->error($validate->getError());
    die;
}

圖片上傳

//圖片上傳功能,前端頁面模板
<html>
    <head>
        <title>圖片上傳測試</title>
    </head>
    <body>
        <form action="" method="POST" enctype="multipart/form-data">
                <input type="file" name="articlepic" >
                <input type="submit">
        </form>
    </body>
</html>
//注意form表單中的enctype屬性填寫,該屬性值爲"multipart/form-data",該部分意爲form表單中的上傳數據不止有文本數據,也有文件等二進制數據,該屬性的默認值爲"application/x-www-form-urlencoded",此時表示上傳前編碼所有數據,不能傳送文件類型的數據
    
//後端模板
    public function addpic()
    {
        $file = request()->file('articlepic');
        if(request()->isPost())
        {
        if($file)
        {
            $info = $file->move(ROOT_PATH.'public'.DS.'static/uploads');
            echo $info->getExtension();	//文件類型
            echo $info->getSavename();	//文件保存名
            echo $info->getFilename();
        }
        else 
        {
            echo "上傳失敗";
            //echo $file->getError();
        }
    }
        return $this->fetch();
    } 
//例如:move函數中需要將文件挪到/public/static/uploads文件夾下,則參數寫爲“  ROOT_PATH.'public'.DS.'static/uploads'  ”即可,

引用驗證碼

驗證碼類的引入

需要引入想對應版本的類;負責會發生引入錯誤
例如,使用TP5.0時,對應版本爲1.*
在TP5.0項目根目錄下打開cmd,官方指導手冊提示輸入

composer require topthink/think-captcha

實測在TP5.0中會報錯,錯誤內容如下:

Warning: Accessing repo.packagist.org over http which is an insecure protocol.
Using version ^3.0 for topthink/think-captcha
./composer.json has been updated
Loading composer repositories with package information
Warning: Accessing repo.packagist.org over http which is an insecure protocol.
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - topthink/think-captcha v3.0.1 requires topthink/framework ^6.0.0 -> satisfiable by topthink/framework[6.0.x-dev, v6.0.0-rc2, v6.0.0-rc3, v6.0.0-rc4] but these conflict with your requirements or minimum-stability.
    - topthink/think-captcha v3.0.0 requires topthink/framework ^6.0.0 -> satisfiable by topthink/framework[6.0.x-dev, v6.0.0-rc2, v6.0.0-rc3, v6.0.0-rc4] but these conflict with your requirements or minimum-stability.
    - topthink/think-captcha v3.0.1 requires topthink/framework ^6.0.0 -> satisfiable by topthink/framework[6.0.x-dev, v6.0.0-rc2, v6.0.0-rc3, v6.0.0-rc4] but these conflict with your requirements or minimum-stability.
    - topthink/think-captcha v3.0.0 requires topthink/framework ^6.0.0 -> satisfiable by topthink/framework[6.0.x-dev, v6.0.0-rc2, v6.0.0-rc3, v6.0.0-rc4] but these conflict with your requirements or minimum-stability.
    - Installation request for topthink/think-captcha ^3.0 -> satisfiable by topthink/think-captcha[v3.0.0, v3.0.1].


Installation failed, reverting ./composer.json to its original content.

原因是由於版本不匹配

正確引入驗證碼類方法:

composer require topthink/think-captcha=1.* 	//ThinkPHP5.0
composer require topthink/think-captcha=2.0		//ThinkPHP5.1

下載成功之後:

Warning: Accessing repo.packagist.org over http which is an insecure protocol.
./composer.json has been updated
Loading composer repositories with package information
Warning: Accessing repo.packagist.org over http which is an insecure protocol.
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing topthink/think-captcha (v1.0.8): Downloading (100%)

    Invalid zip file, retrying...
  - Installing topthink/think-captcha (v1.0.8): Downloading (60%)
Downloading (100%)
Writing lock file
Generating autoload files

之後就可以成功進行驗證碼的使用

PS:ThinkPHP5.0的官方拓展庫版本號爲1.*;ThinkPHP5.1的拓展庫版本號爲2.0;

在模板中顯示驗證碼

<div>
	<img src="{:captcha_src()}" alt="captcha"/>
	<input name="code" text="text" >
</div>

在控制器中操作驗證碼進行驗證

$data = input('code');
if(!captcha_check($data)){
	return $this->error('驗證碼錯誤');
};

實現單擊刷新驗證碼

<img src="{:captcha_src()}" alt="captcha" title="單擊刷新驗證碼"  style="width:120px;float:left" 
 onclick="this.src='{:captcha_src()}?'+Math.random()"/>
<!--{:captcha_src()}爲獲取驗證碼的url,Math.random()爲隨機數函數-->

Session

session的使用,記錄用戶登錄信息

/*
Session::delete();
Session::clear();
區別
delete()可以指定刪除域和刪除內容
clear()清空session中的所有信息
*/

Session::delete('username','think');	//刪除think作用域下的username值
Session::delete('uid');					//刪除當前作用域下的uid值

    
    
    
    /**
     * 刪除session數據
     * @param string|array  $name session名稱
     * @param string|null   $prefix 作用域(前綴)
     * @return void
     */
    public static function delete($name, $prefix = null)
    {
        empty(self::$init) && self::boot();
        $prefix = !is_null($prefix) ? $prefix : self::$prefix;
        if (is_array($name)) {
            foreach ($name as $key) {
                self::delete($key, $prefix);
            }
        } elseif (strpos($name, '.')) {
            list($name1, $name2) = explode('.', $name);
            if ($prefix) {
                unset($_SESSION[$prefix][$name1][$name2]);
            } else {
                unset($_SESSION[$name1][$name2]);
            }
        } else {
            if ($prefix) {
                unset($_SESSION[$prefix][$name]);
            } else {
                unset($_SESSION[$name]);
            }
        }
    }
    
    
    /**
     * 清空session數據
     * @param string|null   $prefix 作用域(前綴)
     * @return void
     */
    public static function clear($prefix = null)
    {
        empty(self::$init) && self::boot();
        $prefix = !is_null($prefix) ? $prefix : self::$prefix;
        if ($prefix) {
            unset($_SESSION[$prefix]);
        } else {
            $_SESSION = [];
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章