HYPHP框架前言

    HYPHP是一款支持中文語法的PHP MVC開發(fā)框架. 它可以幫助你快速開發(fā)PHP應(yīng)用. HYPHP基于Apache2開源協(xié)議發(fā)布 由 和悅網(wǎng)絡(luò)科技團(tuán)隊(duì)進(jìn)行維護(hù)

    框架為了快速開發(fā)PHP應(yīng)用而誕生的.

    框架版本請跟隨GIT GIT 地址 https://github.com/hyyyp/HYPHP2 https://github.com/hyyyp/HYPHP2.git

    HYPHP 是OOP面向?qū)ο罂蚣? 所以需要PHP 5.3+環(huán)境 (包括5.3) 同時(shí)也支持PHP7.0+ HYPHP 數(shù)據(jù)庫操作采用了國外Medoo開源框架. 需要PDO支持! 僅支持PDO!

    基本認(rèn)識

    HYPHP框架 并不需要高大上的服務(wù)器環(huán)境. 框架文件并且輕量簡潔.

    PHP版本要求

    • PHP5.3以上版本 (包括5.3) 框架采用了OOP命名空間

    WEB服務(wù)器與數(shù)據(jù)庫類型要求

    • Windows/ Unix
    • 基礎(chǔ)的Apache / IIS / Nginx 多種WEB環(huán)境
    • 數(shù)據(jù)庫采用了PDO擴(kuò)展, 目前僅支持: MySQL, MariaDB, MSSQL, Oracle, SQLite, PostgreSQL, Sybase

    對于剛接觸的PHP童鞋

    建議你在本地搭建開發(fā)環(huán)境, 推薦幾款: XAMPP , PHPStudy , 本地環(huán)境盡量采用Apache 作為WEB服務(wù)器 較為方便

    開始使用

    訪問框架

    第一次訪問框架, 框架將自動生成應(yīng)用目錄

    根目錄
    ├─Action         控制器目錄
    │  ├─Index.php      生成的Index控制器
    ├─Conf           配置項(xiàng)目錄
    │  ├─config.php      默認(rèn)配置文件
    ├─Lib            自定義類庫目錄
    ├─Model          數(shù)據(jù)庫模型目錄
    ├─Plugin         插件目錄
    ├─Tmp            緩存文件目錄
    ├─View           模板目錄

    框架默認(rèn)會生成一個(gè)Index控制器 (/Action/Index.php) 該文件內(nèi)容為:

    <?php 
    namespace Action;
    use HY\Action;
    class Index extends Action {
        public function Index(){
            echo 'HY框架';
        }
    }

    +++ get:/ <<< success HY框架 +++

    控制器

    控制器的定義

    HYPHP控制器采用了OOP方式進(jìn)行訪問調(diào)用. 控制器就是一個(gè)類, 而操作方法則是一個(gè)類成員函數(shù) 下面是一個(gè)默認(rèn)的 /Action/Index.php 內(nèi)容

    <?php 
    namespace Action;
    use HY\Action;
    class Index extends Action {
        public function Index(){
            echo 'HY框架';
        }
    }

    當(dāng)我們訪問 (如果我們直接訪問首頁 不增加參數(shù) 則會自動指向 Index控制器的Index() 方法)

    +++ get:/ <<< success HY框架 <<<

    +++

    訪問了 /?index 既是訪問了index控制器

    +++ get:/?index <<< success HY框架 <<< +++

    訪問了 /?index/index 既是訪問了index控制器里的index() 方法

    +++ get:/?index/index <<< success HY框架 <<<

    +++

    訪問了 /?index/test 既是訪問了index控制器里的test() 方法

    +++ get:/?index/test <<< Error 你的\Action\IndexAction沒有存在Test操作方法 +++

    當(dāng)訪問test就出錯了 是因?yàn)門est() 并沒有在Index中定義 Index中僅定義了 Index()

    定義一個(gè)新控制器

    控制器的定義采用駝峰法. 首字母大寫. 接下來新建一個(gè) User 控制器 在/Action目錄下新建文件 User.php (注意第一位大寫字母) 在User.php文件寫入內(nèi)容

    <?php 
    namespace Action;
    use HY\Action;
    class User extends Action {
        public function Index(){
            echo '這里是User模塊的Index方法';
        }
    }

    而類的名稱也是一樣采用首字母大寫的方式 User 繼承了 Action

    +++ get:/?User <<< success 這里是User模塊的Index方法 +++

    +++ get:/?User/Index <<< success 這里是User模塊的Index方法 +++ 同理, 如果你僅僅訪問了User控制器 卻沒有輸入Index , 框架還是會自動指向Index()函數(shù), 如果你的User控制器中 沒有Index()函數(shù) 則會出錯


    有朋友不明白 為什么訪問 /?User/Index 就能觸發(fā) Action/User.php文件中的Index函數(shù) 而根目錄并沒有/User目錄呀

    空控制器空函數(shù)

    空控制器 以及 空函數(shù)方法

    當(dāng)訪問了一個(gè)鏈接 /Test/Index 但你的控制器文件中 并沒有Test.php 既是沒有Test控制器 . 則框架會默認(rèn)尋找Action下的No.php控制器

    +++ get:/?Test/Index <<< Error Test控制器不存在! +++

    定義空控制器

    新建一個(gè)空控制器 No.php 放入/Action目錄 并寫入內(nèi)容

    <?php
    namespace Action;
    use HY\Action;
    class No extends Action {
        public function index(){
            echo '你訪問的控制器不存在, 但被Empty接收了';
        }
    }

    我們在訪問

    +++ get:/?Test/Index <<< Success 你訪問的控制器不存在, 但被Empty接收了 +++

    但如果我們訪問 /?Test/Home

    +++ get:/?Test/Home <<< Success 你的\Action\No沒有存在Home操作方法 +++ 就會提示 你的Empty中沒有Home函數(shù)了

    定義空函數(shù)

    我們在Empty中寫入函數(shù) _no _no函數(shù) 可以在任何控制中加入

    <?php
    namespace Action;
    use HY\Action;
    class No extends Action {
        public function index(){
            echo '你訪問的控制器不存在, 但被Empty接收了';
        }
        public function _no(){
            echo '你訪問的函數(shù)未定義';
        }
    }

    再次訪問/Test/Home

    +++ get:/?Test/Home <<< Success 你訪問的函數(shù)未定義 +++ 可見 _no 已經(jīng)接收了 空控制器下的空函數(shù)


    有同學(xué)要問了 怎么獲取訪問進(jìn)來的控制器名以及函數(shù)名呢 框架內(nèi)置了一個(gè)變量 儲存了訪問了URL $_GET['HY_URL']

    $_GET['HY_URL'][0] 則是 控制器名稱 $_GET['HY_URL'][1] 則是 函數(shù)名稱

    顯示模板

    顯示模板 調(diào)用模板

    單純的Action輸出內(nèi)容是有限的, HYPHP內(nèi)置了一個(gè)模板引擎. 默認(rèn)模板目錄位于 /View

    /Action/Index.php # Index控制器編寫一下內(nèi)容

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              $this->display("index");
          }
      }

    /View目錄 新建文件 index.html 寫入內(nèi)容

    Action調(diào)用了這個(gè)模板

    訪問首頁

    +++ get:/

    <<< success Action調(diào)用了這個(gè)模板 +++

    可見訪問了首頁觸發(fā)了 Index 控制器的 Index函數(shù) 并在函數(shù)中調(diào)用了 display 顯示 模板 index

    display('index') 既是調(diào)用了 /View/index.html


    有童鞋問了 模板后綴 .html 能不能更換呢 答: 可以的, 你可以在/Conf/config.php配置中 增加一項(xiàng) 'tpl_suffix' => '.tpl'

    將成為 /View/index.tpl

    中文名稱

    顯示模板();

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              顯示模板("index");
          }
      }

    模板變量賦值

    模板變量賦值 調(diào)用

    當(dāng)我們在Action中輸出了模板. 但模板如何調(diào)用 Action中的變量呢? 看一下下面錯誤的示范 Index 控制器內(nèi)容

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              $string = '這是一個(gè)字符串';
              $this->display("index");
          }
      }

    模板 index.html 內(nèi)容

    我想調(diào)用剛才Action 的 $string 變量 
    輸出變量:  <?php echo $string; ?>

    當(dāng)我們訪問時(shí)

    +++ / <<< Error 調(diào)用了未定義的變量 $string +++ 可見 訪問后 PHP提示出錯 模板調(diào)用了一個(gè) 未定義的變量$string 但控制器中已經(jīng)定義它了呀 在這里說明一下 Action模板 是分離的 模板是不能直接使用 Action的值的 那該咋辦咧


    使用Action成員 v函數(shù) 將變量復(fù)制到模板中

    再次編輯 Index 控制器內(nèi)容

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              $string = '這是一個(gè)字符串';
            $this->v("string",$string);
            $this->v("a",$string);
              $this->display("index");
          }
      }

    $this->v(復(fù)制后名稱,傳入變量)

    index.html 模板內(nèi)容 再次編輯

    我想調(diào)用剛才Action 的 $string 變量 
    輸出變量:  <?php echo $string; ?>
    在增加一個(gè) <?php echo $a; ?>

    再次訪問首頁

    +++ get:/ <<< success 我想調(diào)用剛才Action 的 $string 變量 輸出變量: 這是一個(gè)字符串 在增加一個(gè) 這是一個(gè)字符串 +++ 可見 輸出內(nèi)容中 $a 以及 $string 都變成了 這是一個(gè)字符串


    額外的模板引擎標(biāo)簽 請?jiān)谀0逡婺夸洸榭?/p>

    Json輸出

    Json & Jsonp 輸出 我們通常會在前端用到JSON. 所以框架內(nèi)置了兩個(gè)簡單的 JSON格式化輸出函數(shù)

    Json

    該函數(shù)會更改 Content-Type 類型為 application/json; charset=utf-8

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              $arr = array(1,2,3);
              $this->json($arr);
          }
      }

    +++ get:/ <<< success [1,2,3] +++

    jsonp

    可能新手不懂jsonp是什么意思. jsonp是提供給跨域訪問使用的. 放A網(wǎng)站使用了ajax去獲取 B網(wǎng)站的一個(gè)JSON數(shù)據(jù) 但兩者是不同的域名 造成了 跨域危險(xiǎn). 所以AJax是不能直接通信的 所以只能采用JavaScript腳本的方法 使用函數(shù)去執(zhí)行 格式化遠(yuǎn)程端的字符串JSON

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              $arr = array(1,2,3);
              $this->jsonp($arr,'run');
          }
      }

    +++ get:/ <<< success run([1,2,3]); +++

    URL縮短控制器方法

    縮短控制器

    我們通常定義的控制器 Index User Home ...等等 訪問他們就需要 /index , /user /home 能不能不改變Index的情況下 改變URL中index名稱呢? 就是 訪問 /i 就能訪問到 Index 控制器. HYPHP內(nèi)置了一個(gè)小型控制器以及方法的綁定路由過程


    打開/Conf/config.php 配置文件 增加配置項(xiàng)

    <?php 
      //這是 Conf/config.php 配置文件
      return array(
        'HY_URL'=>array(
            'action'=>array(
                'Index'=>'i',
                'User'=>'u'
            ),
            'method'=>array(
                'Index'=>array(
                    'Index'=>'i'
                )
            )
        ),
      )

    先看 Action 項(xiàng) 'Index' => 'i' 既是將URL中index方法改為了i 通常我們訪問/?Index 現(xiàn)在可以通過 /?i 就可以訪問了 而Method 則是控制器里函數(shù)方法. 將Index() 改為了 i() 通常我們訪問 /?Index/Index 訪問到 Index() 方法 我們現(xiàn)在可以用過 /?Index/i 的方法就訪問到了 Index() 當(dāng)然 你的控制器以及方法都該了 方法將成為 /?i/i 就能訪問到了 /?Index/Index

    URL生成

    為什么需要這個(gè)函數(shù)? 有童鞋覺得是多余的, 太多余麻煩. 是的,作者本人也覺得麻煩, 開發(fā)時(shí)不如直接寫固定連接好了 還要調(diào)用啥函數(shù). 所以這個(gè)函數(shù)是提供給 需要經(jīng)常使用 URL縮短控制器方法的童鞋

    他會通過你的縮短控制器更改去 生成合適的方法

    具體使用方式詳情 : http://bbs.hyphp.cn/t/740.html

    請求類型

    獲取用戶請求類型 通常情況下 我們?yōu)g覽器訪問我們的網(wǎng)站時(shí)都是使用 GET 而提交表單大多都是使用POST 以及JS腳本AJAX訪問 如果在控制器中獲取訪問者的請求類型呢 目前框架已經(jīng)直接內(nèi)置了常量

    常量名 說明
    IS_GET 直接訪問的GET方式
    IS_POST 直接訪問的POST方式
    IS_AJAX 直接訪問的AJAX方式

    目前就內(nèi)置了3個(gè)常用的判斷 他們的值將會是 bool類型

    使用場景演示

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              if(IS_POST)
                echo '用戶采用了POST訪問';
              elseif(IS_GET)
                echo '用戶采用了GET訪問';
              elseif(IS_AJAX)
                  echo '用戶采用了AJAX訪問';
          }
      }

    并不是3個(gè)類型 只有一個(gè)是 true

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              if(IS_POST && IS_AJAX)
                echo '用戶采用了AJAX POST訪問';
    
          }
      }

    模板

    建立模板

    我們開發(fā)時(shí)經(jīng)常會輸出大量的HTML內(nèi)容, 但這些內(nèi)容不可能堆積在控制器中. 所以我們最好使用文件區(qū)分開來. HYPHP內(nèi)置了模板引擎, 提供一些常用的PHP標(biāo)簽以及 組合方式 默認(rèn)模板路徑在 /View ,常量定義為 VIEW_PATH . 建立方式: 模板名 + .后綴 例: (home.html) 控制器中調(diào)用該模板 $this->display("home") .從而輸出 home.html的內(nèi)容 .

    模板后綴名

    可見定義模板時(shí) 使用了 (.html) 框架內(nèi)置的默認(rèn)值為 array(.html , .php) 意為模板可以使用 .html以及.php 如果你想修改該配置 可以從 Conf/config.php 加入 'tpl_suffix' => '.tpl' 或數(shù)組

    使用我們建立的模板

    Index控制器內(nèi)容

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              $this->display("home");
          }
      }

    模板 home.html 內(nèi)容

    這是home模板
    <br>
    第二行文字

    當(dāng)我們訪問時(shí)

    +++ / <<< Success 這是home模板 第二行文字 +++

    模板分組

    通常我們的模板文件都放于模板目錄中. 而太多模板文件堆積在一起 卻看起來很煩惱 所以有必要進(jìn)行分組使用

    建立分組

    通產(chǎn)我們使用的模板目錄位于 /View , 我們可以在該目錄下建立子目錄. 例 : 建立目錄 /View/home , 并新建模板文件在該目錄下

    使用分組

    在控制器方法中 調(diào)用display前 , 將分組名賦值給 : $this->view ,從而框架會通過該變量去增加路徑 (注意大小寫)

    <?php 
    //這是/Action/Index.php 文件
    namespace Action;
    use HY\Action;
    class Index extends Action {
        public function index(){
            //目前顯示模板 /View/index_index.html 
            $this->display('index_index');
        }
        public function test(){
            //將使用 /View/home/index_index.html 模板
            $this->view = 'home';
            $this->display('index_index');
        }
    }

    輸出變量

    當(dāng)我們在控制器輸出模板時(shí), 模板是無法直接調(diào)用方法函數(shù)中的變量的. 我們需要通過框架內(nèi)置的輸出方法, 將變量賦值到模板當(dāng)中使用.

    看一下下面錯誤的示范 Index 控制器內(nèi)容

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              $string = '這是一個(gè)字符串';
              $this->display("index");
          }
      }

    模板 index.html 內(nèi)容

    我想調(diào)用剛才Action 的 $string 變量 
    輸出變量:  <?php echo $string; ?>

    當(dāng)我們訪問時(shí)

    +++ / <<< 出錯 調(diào)用了未定義的變量 $string +++ 可見結(jié)果, 模板是無法直接使用控制器內(nèi)的變量的. 我們需要在控制器方法中 輸出模板時(shí)將變量賦值到模板中 使用Action成員 v函數(shù) 將變量復(fù)制到模板中

    再次編輯 Index 控制器內(nèi)容

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              $string = '這是一個(gè)字符串';
            $this->v("string",$string);
            $this->v("a",$string);
              $this->display("index");
          }
      }

    $this->v(復(fù)制后名稱,傳入變量)

    index.html 模板內(nèi)容 再次編輯

    我想調(diào)用剛才Action 的 $string 變量 
    輸出變量:  <?php echo $string; ?>
    在增加一個(gè) <?php echo $a; ?>
    HYPHP 內(nèi)置標(biāo)簽輸出變量 :  {$a}

    再次訪問首頁

    +++ get:/ <<< success 我想調(diào)用剛才Action 的 $string 變量 輸出變量: 這是一個(gè)字符串 在增加一個(gè) 這是一個(gè)字符串 HYPHP 內(nèi)置標(biāo)簽輸出變量 : 這是一個(gè)字符串 +++ 可見 輸出內(nèi)容中 $a 以及 $string 都變成了 這是一個(gè)字符串


    {$變量名} 輸出變量

    框架的模板引擎提供了一系列輸出標(biāo)簽.

    {$a}
    等同于
    <?php echo $a; ?>

    輸出數(shù)組變量 {$數(shù)組變量.數(shù)組索引}

    Index 控制器內(nèi)容

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              $arr =array(
                'user'=>'admin',
                'pass'=>'123456'
               );
               $this->v('arr',$arr);
              $this->display("index");
          }
      }

    模板 index.html 內(nèi)容

    我想調(diào)用剛才Action 的 $arr 變量 
    輸出變量:  {$arr.user} {$arr.pass}

    當(dāng)我們訪問時(shí)

    +++ / <<< 出錯 我想調(diào)用剛才Action 的 $arr 變量 輸出變量: admin 123456 +++

    包含模板

    包含文件 包含模板 連接模板

    我們之前的介紹都是在控制器中 單獨(dú)輸出了一個(gè)模板文件. 但我們的項(xiàng)目肯定是需要使用到 包含文件的 最常見的就是 HTML的 header 以及footer 或Menu

    使用實(shí)例

    Index控制器內(nèi)容

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              $this->display("index");
          }
      }

    模板 index.html 內(nèi)容

    {include header}
    我是Index模板<br>
    {include footer}

    模板 header.html 內(nèi)容

    我是頭部文件 header <br>

    模板 footer.html 內(nèi)容

    我是尾部文件 footer <br>

    +++ / <<< Success 我是頭部文件 header 我是Index模板 我是尾部文件 footer +++

    {include 模板名}

    可見我們的結(jié)果中. 控制器輸出了index模板 而index中使用了include 包含了header 以及 footer 使用 {include} 是不需要加入模板后綴的.

    判斷標(biāo)簽

    PHP中我們使用的流程控制判斷 大多都是使用 if elseif else

    使用

    Index控制器內(nèi)容

    <?php 
      namespace Action;
      use HY\Action;
      class Index extends Action {
          public function Index(){
              $this->display("index");
          }
      }

    模板 index.html 內(nèi)容

    我是Index模板<br>
    {if '1' == '1'}
    當(dāng)然啦
    {else}
    你中毒不淺
    {/if}
    
    等同于
    
    <?php
    if('1' == '1')
    echo '當(dāng)然啦';
    else
    echo '你中毒不淺';
    ?>

    {if} 允許使用變量 以及 PHP函數(shù). 框架解析后 與 PHP原生是一樣的

    <!-- 注意 if 或者 elseif 后需要空格, 后面才是條件 -->
    {if $a > $b}
    
    {elseif $a > $b}  <!-- elseif 可將它去除 -->
    
    {else}
    
    {/if}
    
    
    <!-- 這是原生的語句 -->
    <?php if (condition): ?>
    
    <?php else: ?>
    
    <?php endif ?>
    
    
    --------if elseif ---------
    
    <?php if (condition): ?>
    
    <?php elseif (condition): ?>
    
    <?php else: ?>
    
    <?php endif ?>
    

    循環(huán)標(biāo)簽

    {for } {foreach}

    與php是一致的標(biāo)簽

    模板文件內(nèi)容

    {for $i=0;$i<10;$i++}
    
    {/for}
    
    <!-- 第二種演示 -->
    {for $i=0,$ii=10;$i<$ii;$i++,$ii--}
    
    {/for}
    
    
    <!-- 原生for -->
    <?php for ($i=0;$i<10;$i++): ?>
        輸出$i : {$i}
    <?php endfor ?>
    
    --------------輸出結(jié)果
    輸出$i : 0
    輸出$i : 1
    輸出$i : 2
    輸出$i : ...
    {foreach $data as $K=>$v}
    
    {/foreach}
    
    {foreach $data as $v}
    
    {/foreach}
    
    
    <!-- 下面是原生foreach -->
    
    
    <?php $arr = array('1','2','3'); ?>
    
    
    <?php foreach ($arr as $key => $value): ?>
        輸出arr : {$value}
    <?php endforeach ?>
    
    ----輸出結(jié)果
    輸出arr : 1
    輸出arr : 2
    輸出arr : 3

    數(shù)據(jù)庫模型

    數(shù)據(jù)庫引擎介紹

    框架采用了國外Medoo作為支持. 它必須采用PHP PDO擴(kuò)展支持, 否則將無法使用 目前框架支持的數(shù)據(jù)庫引擎

    PHP_PDO 擴(kuò)展列表


    • MySQL, MariaDB -> php_pdo_mysql
    • MSSQL (Windows) -> php_pdo_sqlsrv
    • MSSQL (Liunx/UNIX) -> php_pdo_dblib
    • Oracle -> php_pdo_oci
    • SQLite -> php_pdo_sqlite
    • PostgreSQL -> php_pdo_pgsql
    • Sybase -> php_pdo_dblib

    如何開啟PDO

    打開 php.ini 找到你想要的相應(yīng)擴(kuò)展,去掉前面的;號即可

    ;extension=php_pdo_mysql.dll
    // 修改成
    extension=php_pdo_mysql.dll
    // 保存,重啟你的PHP或者服務(wù)器

    如果你是Linux下的PHP環(huán)境 則.dll 為 .so

    連接數(shù)據(jù)庫

    Config 配置 請打開 /Conf/config.php 文件 增加以下信息

    <?php
    
    return array(
        //其他一些配置
        ....
        //數(shù)據(jù)庫類型
        "SQL_TYPE" => "mysql",
        //數(shù)據(jù)庫名稱
        "SQL_NAME" => "test",
        //數(shù)據(jù)庫地址
        "SQL_IP"=>"localhost",
        //數(shù)據(jù)庫賬號
        'SQL_USER' => 'root',
        //數(shù)據(jù)密碼
        'SQL_PASS' => 'root',
        //數(shù)據(jù)庫字符集
        'SQL_CHARSET' => 'utf8',
        //數(shù)據(jù)庫端口
        'SQL_PORT' => 3306,
        //數(shù)據(jù)庫前綴
        'SQL_PREFIX' => 'hy_',
        //PDO配置
        'SQL_OPTION' => array(
            PDO::ATTR_CASE => PDO::CASE_NATURAL,
            //PDO::ATTR_PERSISTENT => true //長連接
        )
    
    );
    名稱 說明
    SQL_TYPE 數(shù)據(jù)庫類型
    SQL_NAME 數(shù)據(jù)庫名稱
    SQL_IP 數(shù)據(jù)庫地址
    SQL_USER 數(shù)據(jù)庫 用戶
    SQL_PASS 數(shù)據(jù)庫 密碼
    SQL_CHARSET 數(shù)據(jù)庫編碼
    SQL_PORT 數(shù)據(jù)庫端口
    SQL_PREFIX 數(shù)據(jù)庫前綴
    SQL_OPTION PDO 額外配置項(xiàng)

    多數(shù)據(jù)庫配置

    配置多數(shù)據(jù)


    /Conf/config.php 增加內(nèi)容

    <?php 
    return array(
        //單個(gè)數(shù)據(jù)庫配置
        //數(shù)據(jù)庫類型
        "SQL_TYPE" => "mysql",
        //數(shù)據(jù)庫名稱
        "SQL_NAME" => "hybbs",
        //數(shù)據(jù)庫地址
        "SQL_IP"=>"localhost",
        //數(shù)據(jù)庫賬號
        'SQL_USER' => 'root',
        //數(shù)據(jù)密碼
        'SQL_PASS' => '',
        //數(shù)據(jù)庫字符集
        'SQL_CHARSET' => 'utf8',
        //數(shù)據(jù)庫端口
        'SQL_PORT' => 3306,
        //數(shù)據(jù)庫前綴
        'SQL_PREFIX' => 'hy_',
        //PDO配置
        'SQL_OPTION' => array(
            PDO::ATTR_CASE => PDO::CASE_NATURAL,
            //PDO::ATTR_PERSISTENT => true //長連接
        ),
    
        //增加多數(shù)據(jù)庫配置
    
        'SQL_MORE'=>array(
             //這個(gè)數(shù)據(jù)庫的名稱
            'caiji'=>array(
                //數(shù)據(jù)庫類型
                "SQL_TYPE" => "mysql",
                //數(shù)據(jù)庫名稱
                "SQL_NAME" => "caiji",
                //數(shù)據(jù)庫地址
                "SQL_IP"=>"localhost",
                //數(shù)據(jù)庫賬號
                'SQL_USER' => 'root',
                //數(shù)據(jù)密碼
                'SQL_PASS' => '',
                //數(shù)據(jù)庫字符集
                'SQL_CHARSET' => 'utf8',
                //數(shù)據(jù)庫端口
                'SQL_PORT' => 3306,
                //數(shù)據(jù)庫前綴
                'SQL_PREFIX' => '',
                //PDO配置
                'SQL_OPTION' => array(
                    PDO::ATTR_CASE => PDO::CASE_NATURAL,
                    //PDO::ATTR_PERSISTENT => true //長連接
                ),
            ),
            //再增加多個(gè)數(shù)據(jù)庫
            //'xxx'=>array('SQL_TYPE' .... ..  . . .)
            //.. ... ..
            //.....
        ),
    );

    和以往的數(shù)據(jù)庫配置一樣 不過他就是放入了 SQL_MORE

    可見 SQL_MORE 中添加了一個(gè) caiji 項(xiàng) caiji 項(xiàng)的數(shù)據(jù)庫信息 包含在caiji數(shù)組中 數(shù)據(jù)庫信息 很直觀 一看就懂

    使用多數(shù)據(jù)庫


    在使用多數(shù)據(jù)庫前一定要配置 SQL_MORE 項(xiàng) 否則無法使用的! 接著上一個(gè)文章 的配置信息

    'SQL_MORE'=>array(
            'name1'=>array(
                //數(shù)據(jù)庫類型
                "SQL_TYPE" => "mysql",
                //數(shù)據(jù)庫名稱
                "SQL_NAME" => "caiji",
                //數(shù)據(jù)庫地址
                "SQL_IP"=>"localhost",
                //數(shù)據(jù)庫賬號
                'SQL_USER' => 'root',
                //數(shù)據(jù)密碼
                'SQL_PASS' => '',
                //數(shù)據(jù)庫字符集
                'SQL_CHARSET' => 'utf8',
                //數(shù)據(jù)庫端口
                'SQL_PORT' => 3306,
                //數(shù)據(jù)庫前綴
                'SQL_PREFIX' => '',
                //PDO配置
                'SQL_OPTION' => array(
                    PDO::ATTR_CASE => PDO::CASE_NATURAL,
                    //PDO::ATTR_PERSISTENT => true //長連接
                ),
            )
        ),

    S M函數(shù)使用

    <?php
    //連接 多個(gè)數(shù)據(jù)庫配置中的 name 數(shù)據(jù)庫. 并操作 他的user 表
    $User = S('user','name');
    

    where條件

    基礎(chǔ) where演示

    使用數(shù)據(jù)庫無時(shí)無刻都需要條件去檢索數(shù)據(jù) . 框架內(nèi)置的where 采用數(shù)組方式傳入解析. 并還原SQL語句進(jìn)行執(zhí)行

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
    
            public function Index(){
                //實(shí)例User表為對象
                $User = S("User");
    
                //滿足email = a 的數(shù)據(jù),并返回 user_name 字段數(shù)組
                $User->select("user_name", array(
                    "email" => "a"
                ));
                // WHERE email = 'a'
    
    
                $User->select(user_name", array(
                    "user_id" => 200
                ));
                // WHERE user_id = 200
    
                $User->select("user_name", array(
                    "user_id[>]" => 200
                ));
                // WHERE user_id > 200
    
                $User->select("user_name", array(
                    "user_id[>=]" => 200
                ));
                // WHERE user_id >= 200
    
                $User->select(user_name", array(
                    "user_id[!]" => 200
                ));
                // WHERE user_id != 200
    
    
    
                $User->select("user_name", array(
                    "age[<>]" => [200, 500]
                ));
                // WHERE age BETWEEN 200 AND 500
    
                $User->select("user_name", array(
                    "age[><]" => [200, 500]
                ));
                // WHERE age NOT BETWEEN 200 AND 500
    
    
                // [><] 和 [<>] 可以用于 datetime
                $User->select("user_name", array(
                    "birthday[><]" => array(
                        date("Y-m-d", mktime(0, 0, 0, 1, 1, 2015)), date("Y-m-d")
                    )
                ));
                //WHERE "create_date" BETWEEN '2015-01-01' AND '2015-05-01' (now)
    
                // 你不僅可以使用字符串和數(shù)字,還可以使用數(shù)組
                $User->select("user_name", array(
                    "OR" => array(
                        "user_id" => [2, 123, 234, 54],
                        "email" => array("foo@bar.com", "cat@dog.com", "admin@medoo.in")
                    )
                ));
                // WHERE
                // user_id IN (2,123,234,54) OR
                // email IN ('foo@bar.com','cat@dog.com','admin@medoo.in')
    
                // 多條件查詢
                $User->select("user_name", array(
                    "AND" => array(
                        "user_name[!]" => "foo",
                        "user_id[!]" => 1024,
                        "email[!]" => ["foo@bar.com", "cat@dog.com", "admin@medoo.in"],
                        "city[!]" => null,
                        "promoted[!]" => true
                    )
                ));
                // WHERE
                // `user_name` != 'foo' AND
                // `user_id` != 1024 AND
                // `email` NOT IN ('foo@bar.com','cat@dog.com','admin@medoo.in') AND
                // `city` IS NOT NULL
                // `promoted` != 1
    
                // 或者嵌套 select() ak  get() 方法
                $User->select("user_name", array(
                    "user_id" => $User->select("post", "user_id", ["comments[>]" => 40])
                ));
                // WHERE user_id IN (2, 51, 321, 3431)
    
            }
    
        }

    AND OR

    上面是基礎(chǔ)的Where語句,下面看一下復(fù)雜一點(diǎn)的 你可以使用"AND" 或 "OR" 來拼接非常復(fù)雜的SQL語句

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
    
            public function Index(){
                //實(shí)例User表為對象
                $User = S("User");
    
                // 基礎(chǔ)使用
                $User->select("user_name", array(
                    "AND" => array(
                        "user_id[>]" => 200,
                        "age[<>]" => array(18, 25),
                        "gender" => "female"
                    )
                ));
                // WHERE user_id > 200 AND age BETWEEN 18 AND 25 AND gender = 'female'
    
                $User->select("user_name", array(
                    "OR" => array(
                        "user_id[>]" => 200,
                        "age[<>]" => array(18, 25),
                        "gender" => "female"
                    )
                ));
                // WHERE user_id > 200 OR age BETWEEN 18 AND 25 OR gender = 'female'
    
                // 復(fù)合條件
                $User->has(array(
                    "AND" => array(
                        "OR" => array(
                            "user_name" => "foo",
                            "email" => "foo@bar.com"
                        ),
                        "password" => "12345"
                    )
                ));
                // WHERE (user_name = 'foo' OR email = 'foo@bar.com') AND password = '12345'
    
                // 注意
                // 因?yàn)槭褂玫氖菙?shù)組傳參,所以下面這種用法是錯誤的。
                // 可見 你有兩個(gè)OR ,數(shù)組不可能存在兩個(gè)相同索引. 所以你需要將另一個(gè)OR 加上一個(gè)注釋
                $User->select('*', array(
                    "AND" => array(
                        "OR" => array(
                            "user_name" => "foo",
                            "email" => "foo@bar.com"
                        ),
                        "OR" => array(
                            "user_name" => "bar",
                            "email" => "bar@foo.com"
                        )
                    )
                ));
                // [X] SELECT * FROM "account" WHERE ("user_name" = 'bar' OR "email" = 'bar@foo.com')  這是錯誤的示范
    
                // 正確的方式是使用如下方式定義復(fù)合條件
                $User->select('*', array(
                    "AND #Actually, this comment feature can be used on every AND and OR relativity condition" => array(
                        "OR #the first condition" => array(
                            "user_name" => "foo",
                            "email" => "foo@bar.com"
                        ),
                        "OR #the second condition" => array(
                            "user_name" => "bar",
                            "email" => "bar@foo.com"
                        )
                    )
                ));
                // SELECT * FROM "account"
                // WHERE (
                //  (
                //      "user_name" = 'foo' OR "email" = 'foo@bar.com'
                //  )
                //  AND
                //  (
                //      "user_name" = 'bar' OR "email" = 'bar@foo.com'
                //  )
                // )
    
            }
        }
    

    LINK 模糊查找條件

    接下來我們看一下模糊匹配 Like語句 LIKE 使用語法 [~] .

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
    
            public function Index(){
                //實(shí)例User表為對象
                $User = S("User");
    
                // 默認(rèn)情況下,使用%在前后包含關(guān)鍵詞
                $User->select("id", array(
                    "city[~]" => "lon"
                ));
    
                WHERE "city" LIKE '%lon%'
    
                // 數(shù)組形式,查詢多個(gè)關(guān)鍵詞
                $User->select("id", array(
                    "city[~]" => array("lon", "foo", "bar")
                ));
    
                WHERE "city" LIKE '%lon%' OR "city" LIKE '%foo%' OR "city" LIKE '%bar%'
    
                // 不包含 [!~]
                $User->select("id", array(
                    "city[!~]" => "lon"
                ));
    
                WHERE "city" NOT LIKE '%lon%'
    
                // 使用SQL自帶的一些通配符
                // 你可以使用sql自帶的一些通配符來完成較復(fù)雜的查詢
                $User->select("id", array(
                    "city[~]" => "stan%" // Kazakhstan,  Uzbekistan, Türkmenistan
                ));
    
                $User->select("id", array(
                    "city[~]" => "Londo_" // London, Londox, Londos...
                ));
    
                $User->select("id", array(
                    "name[~]" => "[BCR]at" // Bat, Cat, Rat
                ));
    
                $User->select("id", array(
                    "name[~]" => "[!BCR]at" // Eat, Fat, Hat...
                ));
    
    
            }
    
        }

    ORDER排序

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
    
            public function Index(){
                //實(shí)例User表為對象
                $User = S("User");
    
                $User->select("user_id", array(
    
                    // "ORDER" => "age DESC"
                    "ORDER" => ['age'=>'DESC'],
    
                ));
                //  SELECT user_id FROM account
                //  ORDER BY age
    
                // 多個(gè)排序
                $User->select("user_id", array(
    
                    "ORDER" => array('user_name DESC', 'user_id ASC')
    
                ));
                //  SELECT user_id FROM account
                //  ORDER BY "user_name" DESC, "user_id" ASC
    
    
                // 根據(jù)字段自定義排序順序
                // "ORDER" => array("column_name", [array #ordered array])
                $User->select("user_id", array(
    
                    "user_id" => array(1, 12, 43, 57, 98, 144),
    
                    "ORDER" => array("user_id", array(43, 12, 57, 98, 144, 1))
    
                ));
                // SELECT "user_id"
                // FROM "account"
                // WHERE "user_id" IN (1,12,43,57,98,144)
                // ORDER BY FIELD("user_id", 43,12,57,98,144,1)
    
                // array(6) {
                //  [0]=> string(2) "43"
                //  [1]=> string(2) "12"
                //  [2]=> string(2) "57"
                //  [3]=> string(2) "98"
                //  [4]=> string(3) "144"
                //  [5]=> string(1) "1"
                // }
    
            }
    
        }

    MATCH 多鍵搜索

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
    
            public function Index(){
                //實(shí)例User表為對象
                $User = S("User");
    
    
                //搜索一個(gè)用戶 可能user 或者 email中存在關(guān)鍵字
                $User->select("post_id", array(
                    "MATCH" => array(
                        "columns" => array("user", "email"),
                        "keyword" => "foo"
                    )
                );
                // WHERE MATCH (content, title) AGAINST ('foo')
    
            }
    
        }

    數(shù)據(jù)庫內(nèi)置函數(shù)

    在一些特殊的情況下,你可能需要使用SQL系統(tǒng)函數(shù),只需要字段名前加上#號即可

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
    
            public function Index(){
                //實(shí)例User表為對象
                $User = S("User");
    
                $data = $User->select( array(
                    'user_id',
                    'user_name'
                ), array(
                    '#datetime' => 'NOW()'
                ));
    
                // SELECT "user_id","user_name"
                // FROM "account"
                // WHERE "datetime" = NOW()
    
                // [重要]記住,價(jià)值也不會引用應(yīng)符合xxx()大寫。
                //下面是一個(gè)錯誤的示例
                $User->select(array(
                    'user_id',
                    'user_name'
                ), array(
                    '#datetime2' => 'now()',
    
                    'datetime3' => 'NOW()',
    
                    '#datetime4' => 'NOW'
                ));
    
            }
    
        }

    LIMIT

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
    
            public function Index(){
                //實(shí)例User表為對象
                $User = S("User");
    
                $User->select("account", "user_id", array(
                    "GROUP" => "type",
    
                    // 必須有使用它與小組一起
                    "HAVING" => array(
                        "user_id[>]" => 500
                    ),
    
                    // LIMIT => 20
                    "LIMIT" => array(20, 100)
                ));
                //  SELECT user_id FROM account
                //  GROUP BY type
                //  HAVING user_id > 500
                //  LIMIT 20,100
    
            }
    
        }

    Select

    Select 選擇器

    數(shù)據(jù)庫查詢

    select( $columns, $where) columns [string/array] 要查詢的字段名. where (optional) [array] 查詢的條件.


    select($join, $columns, $where) join [array] 多表查詢,不使用可以忽略. columns [string/array] 要查詢的字段名. where (optional) [array] 查詢的條件.


    返回: [array] 你可以使用*來匹配所有字段, 但如果你指名字段名可以很好的提高性能.

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
    
            public function Index(){
                //實(shí)例User表為對象
                $User = S("User");
    
                $datas = $User->select(array(
                    "user_name",
                    "email"
                ), array(
                    "user_id[>]" => 100
                ));
                //返回?cái)?shù)據(jù)
                // $datas = array(
                //  [0] => array(
                //      "user_name" => "admin1",
                //      "email" => "admin1"
                //  ),
                //  [1] => array(
                //      "user_name" => "admin2",
                //      "email" => "admin2"
                //  )
                // )
    
    
                foreach($datas as $data)
                {
                    echo "user_name:" . $data["user_name"] . " - email:" . $data["email"];
                }
    
                // 查詢所有字段 使用 *
                $datas = $database->select("*");
    
                // 查詢一個(gè)字段 輸入他的字段名稱
                $datas = $database->select("user_name");
    
                // $datas = array(
                //  [0] => "admin1",
                //  [1] => "admin2"
                // )
    
            }
    
        }

    多表查詢

    多表查詢

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
    
            public function Index(){
                //實(shí)例User表為對象
                $User = S("User");
    
    
                // [>] == LEFT JOIN
                // [<] == RIGH JOIN
                // [<>] == FULL JOIN
                // [><] == INNER JOIN
    
                $User->select("post", array(
                    // Here is the table relativity argument that tells the relativity between the table you want to join.
    
                    // The row author_id from table post is equal the row user_id from table account
                    "[>]account" => array("author_id" => "user_id"),
    
                    // The row user_id from table post is equal the row user_id from table album.
                    // This is a shortcut to declare the relativity if the row name are the same in both table.
                    "[>]album" => "user_id",
    
                    // [post.user_id is equal photo.user_id and post.avatar_id is equal photo.avatar_id]
                    // Like above, there are two row or more are the same in both table.
                    "[>]photo" => array("user_id", "avatar_id"),
    
                    // If you want to join the same table with different value,
                    // you have to assign the table with alias.
                    "[>]account (replyer)" => array("replyer_id" => "user_id"),
    
                    // You can refer the previous joined table by adding the table name before the column.
                    "[>]account" => array("author_id" => "user_id"),
                    "[>]album" => array("account.user_id" => "user_id"),
    
                    // Multiple condition
                    "[>]account" => array(
                        "author_id" => "user_id",
                        "album.user_id" => "user_id"
                    )
                ), array(
                    "post.post_id",
                    "post.title",
                    "account.user_id",
                    "account.city",
                    "replyer.user_id",
                    "replyer.city"
                ), array(
                    "post.user_id" => 100,
                    "ORDER" => "post.post_id DESC",
                    "LIMIT" => 50
                ));
    
                // SELECT
                //  `post`.`post_id`,
                //  `post`.`title`,
                //  `account`.`city`
                // FROM `post`
                // LEFT JOIN `account` ON `post`.`author_id` = `account`.`user_id`
                // LEFT JOIN `album` USING (`user_id`)
                // LEFT JOIN `photo` USING (`user_id`, `avatar_id`)
                // WHERE
                //  `post`.`user_id` = 100
                // ORDER BY `post`.`post_id` DESC
                // LIMIT 50
    
            }
    
        }

    舉一個(gè)通俗易懂的例子 兩個(gè)表 post 與 user

    post表的數(shù)據(jù)

    id uid title
    1 1 文章標(biāo)題
    2 1 文章標(biāo)題
    3 1 文章標(biāo)題

    user表的數(shù)據(jù) | uid | username | | --- | --- | | 1 | admin | | 2 | xxxx | | 3 | dddd |

    問題: 如果獲取 post表數(shù)據(jù)的時(shí)候 同時(shí)獲取 用戶名 (user.username) 答: 簡單的都是先獲取了 post的數(shù)據(jù)出來 再循環(huán)user表中的username

    我們?nèi)〕鰌ost表的數(shù)據(jù)時(shí) 還能取出uid 用戶ID 卻不能取出用戶名, 這時(shí)就能用到多表查詢

    S('Post')->select(array(
          "[>]user" => [ "uid" => "uid"], //post.uid == user.uid 
      ),array(
          'post.title',
          'user.username'
      )
    );
    輸出:
    arrary(
        'title'=>'文章標(biāo)題',
        'username'=>'admin'
    )

    多表查詢 Count

    S('Post')->count(array(
          "[>]user" => [ "uid" => "uid"], //post.uid == user.uid 
      ),
      '*'
    );

    復(fù)雜的多表查詢 Count (HYBBS處的一段搜索代碼)

    $page_count = $Thread->count(
      array(
          "[>]post" => [ "pid" => "id"], //post.id == thread.pid
      ),
      '*',
      array('AND'=>array(
        'isthread'=>1
        ,'OR'=>array(
          'thread.title[~]'=>$key,
          'post.content[~]'=>$key
      )))
    );

    OBJ->count($join, "*" ,條件 );

    Insert 插入數(shù)據(jù)

    insert($data) 中文 : 插入($data) data [array] 插入到表里的數(shù)據(jù) Return: [number] 返回插入的id

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
            public function Index(){
                //實(shí)例User表為對象
                $User = S("User");
    
    
                $User->insert(array(
                    "user" => "admin",
                    "pass" => "admin",
                ));
                //返回插入的ID
                $User->id();
                //中文語法
                $User->插入(array(
                    "user" => "admin",
                    "pass" => "admin",
                ));
    
            }
    
        }

    插入多條數(shù)據(jù)

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
    
            public function Index(){
                //實(shí)例User表為對象
                $User = M("User");
    
                $id = $User->insert(array(
                    array(
                        "user" => "admin",
                        "pass" => "admin",
    
                    ),
                    array(
                        "user" => "admin1",
                        "pass" => "admin1",
    
                    )
                ));
            }
    
        }

    Update 更新數(shù)據(jù)

    update($data, $where) 中文 : 更新(數(shù)據(jù),條件) data [array] 修改的數(shù)據(jù). WHERE 條件.[可選] Return: [number] 受影響的行數(shù).

    $User = S("User");
    $User->update(array(
        "type" => "user",
    
        // age字段的值 + 1
        "age[+]" => 1,
    
        // 減 - 5
        "level[-]" => 5,
    
        // 兩倍 2
        "score[*]" => 2,
    
        // SQL 函數(shù)
        "#uid" => "UUID()"
    ), array(
        "user_id[<]" => 1000
    ));

    將 用戶名user 等于 admin的用戶密碼修改為 123

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
    
            public function Index(){
                //實(shí)例User表為對象
                $User = M("User");
    
    
                $User->update(
                  array(
                      "pass" => "123",
                  ),
                  array(
                      'user'=>'admin'
                  )
                );
                //中文
                $User->更新(
                  array(
                      "pass" => "123",
                  ),
                  array(
                      'user'=>'admin'
                  )
                );
    
    
            }
    
        }

    Delete 刪除數(shù)據(jù)

    delete($where) 中文 : 刪除(條件); where [array] WHERE 刪除條件. Return: [number] 返回被刪除的行數(shù).

    刪除一個(gè) user = admin 并 年齡<18的數(shù)據(jù)

    $User = S("User");
    $User->delete(array(
        "AND" => array(
            "user" => "admin"
            "age[<]" => 18
        )
    ));
    //中文語法
    $User->刪除(array(
        "AND" => array(
            "user" => "admin"
            "age[<]" => 18
        )
    ));

    刪除 user 等于 admin的數(shù)據(jù)

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
    
            public function Index(){
                //實(shí)例User表為對象
                $User = S("User");
                $User->delete(
                  array(
                      "user" => "admin",
                  )
                );
    
            }
    
        }

    Find

    通過條件查詢,將返回一條記錄

    find($columns, $where) 中文 : 查找(返回字段, 條件); columns [string/array] 返回的字段列. where (optional) [array] WHERE 條件. Return: [string/array] 返回查詢到的數(shù)據(jù).

    //查找 user 等于 admin的數(shù)據(jù) 并返回pass
    $User = S("User");
    $pass = $User->find("pass", array(
        "user" => "admin"
    ));
    
    //查找條件與上一致  返回 更多字段的數(shù)據(jù)
    $data = $User->find(array(
        "email",
        "user",
        "pass"
    ), array(
        "user" => "admin"
    ));
    
    // $data = array(
    //  "email" => "admin@a.com",
    //  "user" => "admin",
    //  "pass" => "admin"
    // )
    
    $pass = $User->find("*", array(
        "user" => "admin"
    ));
    //返回 所有字段
    
    //中文語法
    $User = S("User");
    $pass = $User->查找("pass", array(
        "user" => "admin"
    ));
    
    

    Has

    通過條件搜素 判斷數(shù)據(jù)是否存在

    has($where) 中文 : 是否存在(條件); where [array] WHERE 條件. Return: [boolean] 返回 TRUE 或者 FALSE.


    has($join, $where) join [array] 多表查詢. where [array] WHERE條件.


    Return: [boolean] 返回 TRUE 或者 FALSE.

    例:可以使用它來判斷某用戶是否存在 , 或者賬號密碼是否正確!

    $User = S("User");
    // 判斷用戶賬號密碼是否正確, 可見 user = admin && pass = admin
    if ($User->has(array(
        "AND" => array(
            "user" => "admin",
            "pass" => "admin"
        )
    ))){
        echo "正確";
    }
    else{
        echo "不正確";
    }
    
    //判斷賬號是否存在
    if ($User->has(array(
        "user" => "admin",
    )))
        echo '存在';
    else
        echo '不存在';
    

    Count

    通過條件 檢索數(shù)據(jù)的數(shù)量

    count($where) 中文 : 總數(shù)(條件); where (optional) [array] WHERE 條件.


    count( $join, $column, $where) join [array] 多表查詢. column [string] 需要統(tǒng)計(jì)的字段. where (optional) [array] WHERE 條件.


    Return: [number] 行的數(shù)量. 返回的是數(shù)字類型.

    $User = S("User");
    
    //查看 user = admin 有多少數(shù)目
    $count = $User->count(array(
        "user" => "admin"
    ));
     //查找User表的數(shù)據(jù)總數(shù)
     $All_count = $User->count();

    Max Min

    max($column, $where) 中文語法 : 最大值() / 最小值() column [string] 查詢的字段列. where (optional) [array] WHERE 條件.


    max($join, $column, $where) join [array] 多表查詢. column [string] 字段名. where (optional) [array] 條件.


    Return: [number] 返回最大的值.

    查詢數(shù)據(jù)表中某整數(shù)字段的 最大值. 例如User表有一個(gè)年齡字段

    $User = S("User");
    //查看 age 字段最大值.
    $max = $User->max("age");
    
    //增加條件檢索
    //user=admin的數(shù)據(jù) age 最大值
    $max = $User->max("age",array(
        'user' = 'admin'
    ));

    參數(shù)同Max 查詢數(shù)據(jù)表中某整數(shù)字段的 最小值 用法與Max一致

    Action 事務(wù)操作

    action( $callback ) $callback [function] 事務(wù)內(nèi)執(zhí)行的方法.

    $User = S("User");
    $User->action(function($User) {
        $User->insert('User',array(
            "user" => "admin",
            "pass" => "admin"
        ));
        return true; //false 回滾
    });

    Query

    query($query) query [string] The SQL query. Return: [object] The PDOStatement object.

    $User = S("User");
    $User->query("CREATE TABLE table (
        c1 INT STORAGE DISK,
        c2 INT STORAGE MEMORY
    ) ENGINE NDB;");
    
    $data = $User->query("SELECT email FROM account")->fetchAll();
    print_r($data);

    PDO對象

    //$Model -> pdo
    $User = S("User");
    $User->pdo->query("CREATE TABLE table (
        c1 INT STORAGE DISK,
        c2 INT STORAGE MEMORY
    ) ENGINE NDB;");
    
    $data = $User->pdo->query("SELECT email FROM account")->fetchAll();
    print_r($data);

    Quote 字符串轉(zhuǎn)義

    quote($string) $string [string] 字符串. Return: [string]

    可用于過濾字符串的SQL注入

    $User = M("User");
    
    $string = 'Nice';
    print "Unquoted string: $string\n";
    print "Quoted string: " . $User->quote($string) . "\n";
    
    以上例程會輸出:
    
    Unquoted string: Nice
    Quoted string: 'Nice'
    
    
    /* Dangerous string */
    $string = 'Naughty \' string';
    print "Unquoted string: $string\n";
    print "Quoted string:" . $User->quote($string) . "\n";
    
    以上例程會輸出:
    
    Unquoted string: Naughty ' string
    Quoted string: 'Naughty '' string'
    
    /* Complex string */
    $string = "Co'mpl''ex \"st'\"ring";
    print "Unquoted string: $string\n";
    print "Quoted string: " . $User->quote($string) . "\n";
    
    以上例程會輸出:
    
    Unquoted string: Co'mpl''ex "st'"ring
    Quoted string: 'Co''mpl''''ex "st''"ring'

    Model 定義

    什么是Model , 當(dāng)我們有大量的SQL需要重復(fù)執(zhí)行, 不適合在控制器中大量的寫入. 我們就需要將他們封裝成函數(shù).

    比如我們有一段 添加用戶賬號密碼進(jìn)入用戶表的代碼 . 這代碼可能會在多個(gè)控制器中使用. 此時(shí)我們就可以將這段代碼封裝到Model中.

    Model的定義與控制器Action 是一樣的操作 Model 默認(rèn)存放目錄在 /Model. 我們實(shí)例一個(gè)

    寫入內(nèi)容 Model定義方式與Action一致 首字母大寫.

    新建文件 /Model/User.php

    <?php
    namespace Model;
    use HY\Model;
    !defined('HY_PATH') && exit('HY_PATH not defined.');
    class User extends Model{
        public function test(){
            echo '這是UserModel的test函數(shù)';
        }
    }

    上面就是一個(gè)簡單的Model 類 與 方法函數(shù) 我們嘗試在控制器中使用它

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
            public function Index(){
                //實(shí)例UserModel
                $User = M("User");
                //調(diào)用UserModel 中的 test() ;
                $User->test();
                //對User表插入數(shù)據(jù)
                $User->insert(array(
                    "user" => "admin",
                    "pass" => "admin",
                ));
            }
        }

    +++ get:/ <<< success 這是UserModel的test函數(shù) +++

    更多Model 實(shí)例演示

    /Model/User.php 內(nèi)容

    <?php
    namespace Model;
    use HY\Model;
    !defined('HY_PATH') && exit('HY_PATH not defined.');
    class User extends Model{
        //一個(gè)添加用戶的函數(shù)
        public function add_info($user,$pass){
            $this->insert(array(
              "user" => $user,
              "pass" => $pass,
            ));
        }
        //刪除某用戶函數(shù)
        public function del_user($user){
            $this->delete(array(
                'user'=>$user
            ))
        }
    }

    控制器中使用

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
            public function Index(){
                //實(shí)例UserModel
                $User = M("User");
                //調(diào)用UserModel 中的 add_info() ;
                //添加一個(gè)用戶
                $User->add_info('admin','123456');
    
                //刪除 admin 用戶
                $User->del_user('admin');
    
            }
        }

    Model 調(diào)試模式

    Model上的 debug()方法 可以對該條語句不執(zhí)行 并輸出該語句所生成的SQL語句

    $id = $User->debug()->insert(array(
      "user" => "admin",
      "pass" => "admin",
    ));
    //輸出 
    INSERT INTO "hy_user" ("user", "pass") VALUES ('admin', 'admin')
    
    //中文語法
    $id = $User->調(diào)試()->插入(array(
      "user" => "admin",
      "pass" => "admin",
    ));

    查詢緩存

    通常我們在使用select和find的時(shí)候,希望查詢結(jié)果緩存下來,但是又需要調(diào)用cache(), 還要寫判斷語句,為了避免這種麻煩,HYPHP 直接在Model中內(nèi)置了 查詢緩存。

    通常使用Select

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
            public function Index(){
                $User = S("User");
                $User->select('user',array(
                    "uid" =>1,
                ));
            }
        }

    上面的代碼 select 獲取user表 uid為1的用戶 這是一個(gè)我們常用的查詢方法。而且是固定的結(jié)果。 但是每次訪問都必須執(zhí)行這個(gè)SQL去獲取。 所以會消耗服務(wù)器資源。 所以我們有必要將這個(gè)查詢結(jié)果緩存下來。

    使用查詢緩存

    S()->cache($key,$expire=NULL)->select() ->cache(緩存鍵名,緩存過期時(shí)間)->select()

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
            public function Index(){
                $User = S("User");
                $User->cache('user',10)->select('user',array(
                    "uid" =>1,
                ));
            }
        }

    上面的代碼 緩存10秒這個(gè)select查詢得到的數(shù)據(jù) 緩存鍵名為user

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
            public function Index(){
                $User = S("User");
                $User->cache(true,10)->select('user',array(
                    "uid" =>1,
                ));
            }
        }

    ->cache(true,10) 緩存鍵名填寫 true 則會按照這條sql做 自動補(bǔ)充鍵名。

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
            public function Index(){
                $User = S("User");
                $User->cache(true)->select('user',array(
                    "uid" =>1,
                ));
            }
        }

    看到上面代碼,cache沒有輸入過期時(shí)間。則該緩存會永久緩存

    自定義類庫

    Lib 自定義類庫

    Lib 可以在多種場景中使用, 包括Action,Model,View 中 默認(rèn)Lib目錄處于 /Lib . 新建文件 /Lib/User.php (注意大小寫 首字母必須大寫)

    定義 Lib

    <?php
    namespace Lib;
    class User{
        public function check_user($user){
            $len = strlen($user);
            if($len < 6 || $len > 18)
                return false; //'賬號長度不符合標(biāo)準(zhǔn),必須 大于6位 小于18位'
            return true;
        }
    }

    控制器中使用Lib

    <?php
        namespace Action;
        use HY\Action;
        class Index extends Action {
            public function Index(){
                //實(shí)例UserLib
                $UserLib = L("User");
                $user = 'admin';
                $bool = $UserLib->check_user($user);
                if($bool)
                    echo '用戶名格式正確';
                else
                    echo '反之';
    
            }
        }
    

    框架內(nèi)置函數(shù)

    X 獲取預(yù)定義變量

    獲取 PHP預(yù)定義變量 框架內(nèi)置了一個(gè)函數(shù) 可以獲取提交到服務(wù)器的參數(shù)數(shù)據(jù).

    X() 函數(shù)

    函數(shù)聲明 X(獲取類型,默認(rèn)值='');

    X 函數(shù)可以獲取 _GET _POST _SESSION _COOKIE _SERVER 數(shù)據(jù). 并且你不需要再去使用isset 去判斷索引是否存在 以及 empty 去判斷是否為空 如果 X 函數(shù)返回假 說明不存在

    使用實(shí)例

    類型 原方式 運(yùn)用方式
    post $_POST['參數(shù)名'] X('post.參數(shù)名')
    get $_GET['參數(shù)名'] X('get.參數(shù)名')
    cookie $_COOKIE['參數(shù)名'] X('cookie.參數(shù)名')
    session $_SESSION['參數(shù)名'] X('session.參數(shù)名')
    server $_SERVER['參數(shù)名'] X('server.參數(shù)名')

    控制器中使用

    <?php
        namespace Action;
        use HY\Action;
        class IndexAction extends Action {
            public function Index(){
                echo X("get.id");
                echo X('get.xxxx',0); //如果沒設(shè)置get參數(shù)xxxx 則返回默認(rèn)值0
            }
        }
    

    訪問Index控制器 +++ get:/?id=1 <<< success 1 0 +++

    S 與 M 函數(shù)

    # S 與 M 函數(shù)

    大家在之前的文檔中 會經(jīng)常看到 M("User") 的出現(xiàn) M() 是框架一個(gè)內(nèi)置的函數(shù)

    M 函數(shù)介紹

    M 函數(shù)用于加載你的 Model 類 并且實(shí)例這個(gè)表作為對象操作.

    <?php
        namespace Action;
        use HY\Action;
        class IndexAction extends Action {
            public function Index(){
                //使用 M 函數(shù)對 User 數(shù)據(jù)表 進(jìn)行操作
                $User = M("User");
    
                //插入數(shù)據(jù)
                $User->insert ... ..
                ....
                ..
                關(guān)于 SQL操作  請?jiān)跀?shù)據(jù)庫模型中查看
    
    
            }
        }
    

    S 函數(shù) (默認(rèn)使用)

    該函數(shù)在之前的文檔中 沒有提過 也沒有進(jìn)行過使用. 該函數(shù)與S 函數(shù)差不多 S函數(shù) 是不加載你的自定義Model模型 跳過Model 的加載 直接加載系統(tǒng)底層操作對象類 所以使用S函數(shù)加載的對象 是操作不了Model的內(nèi)容的

    為什么增加一個(gè)S 函數(shù)? 既然與M 差不多

    當(dāng)我們的Model封裝了太多的 函數(shù)后 我們有時(shí)候操作簡單的SQL 并不會使用到Model的內(nèi)容是 我們就可以使用S函數(shù) 跳過Model的加載 提升效率

    <?php
        namespace Action;
        use HY\Action;
        class IndexAction extends Action {
            public function Index(){
                //使用 S 函數(shù)對 User 數(shù)據(jù)表 進(jìn)行操作
                $User = S("User");
    
                //插入數(shù)據(jù)
                $User->insert ... ..
    
    
            }
        }
    

    C 獲取config配置

    C 函數(shù)

    C 函數(shù)可以獲取你在 /Conf/config.php 配置的值 你也可以臨時(shí)將值儲存 但他不會保存到你的config.php中哦! 你可以重復(fù)設(shè)置同一個(gè)值 進(jìn)行覆蓋

    使用實(shí)例

    <?php
        namespace Action;
        use HY\Action;
        class IndexAction extends Action {
            public function Index(){
                //獲取
                echo C("url_explode"); //獲取 URL分隔符
                echo C("SQL_IP"); //獲取 數(shù)據(jù)庫地址
    
                //設(shè)置
                C('TEST','123');
                C(array(
                    'TEST'=>'123',
                    'AAA'=>'zxc'
                ));
    
                //獲取
                echo C('TEST'); //輸出 123
                echo C('AAA'); //輸出 zxc
            }
        }
    

    A 調(diào)用另一個(gè)控制器方法

    A 函數(shù)

    我們開發(fā)時(shí)肯定會有很多個(gè)控制器 存放于 Action中 但如果我們想在 Index控制器 中調(diào)用 Home控制器 里的函數(shù)怎么辦咧? 使用A函數(shù)

    實(shí)例

    這是Index控制器內(nèi)容

    <?php
        namespace Action;
        use HY\Action;
        class IndexAction extends Action {
            public function Index(){
                echo '我是Index控制器的Index()方法 <br>';
                //我們調(diào)用一下 Home控制器的 test 方法
                A('Home')->test();
    
                //我們可以將 A 儲存為對象
                $HomeAction = A("Home");
                $HomeAction->test();
            }
        }
    

    這是Home控制器內(nèi)容

    <?php
        namespace Action;
        use HY\Action;
        class HomeAction extends Action {
            public function test(){
                echo '我是Home控制器的test()方法 <br>' ;
            }
        }

    我們訪問一下 Index 控制器 看一下結(jié)果 +++ get:/ <<< success 我是Index控制器的Index()方法 我是Home控制器的test()方法 我是Home控制器的test()方法 +++ End

    cookie 與 session 函數(shù)

    Cookie 函數(shù)

    該函數(shù)復(fù)制與 ThinkPHP .

    Cookie 是我們最常用的操作 將數(shù)據(jù)存儲在 用戶瀏覽器上, 并且可以設(shè)置有效期.

    cookie($name='', $value='',$expire=0) $name : cookie字段 [可選] $value : 設(shè)置cookie值 [可選] $expire : cookie有效期 [可選] 0 等于永遠(yuǎn) 如果3個(gè)參數(shù)都輸入 直接調(diào)用cookie 會直接返回所有cookie .作為數(shù)組返回 相當(dāng)于返回整個(gè) $_COOKIE

    使用實(shí)例

    <?php
        namespace Action;
        use HY\Action;
        class IndexAction extends Action {
            public function Index(){
                //獲取cookie值
                $user = cookie('user'); //儲存在用戶瀏覽器的user字段
    
                //設(shè)置cookie值
                cookie('user','admin');
    
                //設(shè)置cookie值 并 設(shè)置有效期
                //單位是秒
                // 設(shè)置cookie user 只有60秒
                cookie('user','admin',60);
    
                //刪除cookie
                //將第二參數(shù) 設(shè)置為 null 即為刪除 user字段
                cookie('user',null);
            }
        }
    

    session

    session 與cookie不同. cookie 的數(shù)據(jù)是保存在 用戶瀏覽器那邊的, 所以懂點(diǎn)技術(shù)的用戶是可以看到cookie 的內(nèi)容的. 而session的數(shù)據(jù)是儲存在 服務(wù)器的, 用戶是無法直接看到 session儲存的數(shù)據(jù)的

    session 還是需要通過cookie儲存一個(gè)索引在用戶瀏覽器中 從而session從這個(gè)索引中找到 屬于這個(gè)用戶的數(shù)據(jù)

    使用實(shí)例

    <?php
        namespace Action;
        use HY\Action;
        class IndexAction extends Action {
            public function Index(){
                //使用session 時(shí)一定要先啟動session
                //啟動session
                session('[start]'); //啟動了這步 才能操作session  這個(gè)步驟請勿多次使用 每次執(zhí)行只能使用一次
    
                //獲取session值
                echo session('user');
    
                //設(shè)置session值
                session('user','admin');
    
                //刪除session值
                session('user',null);
    
                //返回所有 session 等同于$_SESSION
                print_r(session());
    
    
    
    
    
            }
        }
    

    E 函數(shù)

    該函數(shù)較為少用 用于終止PHP運(yùn)行 并拋出PHP錯誤進(jìn)行提醒

    該函數(shù)不是exit 以及 die 而是 throw new \Exception($str);

    cache 數(shù)據(jù)緩存

    cache 數(shù)據(jù)緩存 HYPHP內(nèi)置了 THINKPHP 的 數(shù)據(jù)緩存類 系統(tǒng)目前已經(jīng)支持的緩存類型包括:Apachenote、Apc、Db、Eaccelerator、File、Memcache、Redis、Shmop、Sqlite、Wincache和Xcache。

    默認(rèn)會使用使用File緩存類型. 將你的數(shù)據(jù)儲存到 /Tmp目錄中 作為文件儲存

    配置你的數(shù)據(jù)緩存類型 配置信息請?zhí)顚懺?/Conf/config.php 中

    以下是配置實(shí)例

    <?php
    return array(
        'DATA_CACHE_TYPE'    =>    'File',
        'DATA_CACHE_TIME'    =>    0,
        'DATA_CACHE_TABLE'    =>    'cache',
        'DATA_CACHE_PREFIX'    =>    '',
        'DATA_CACHE_COMPRESS'    =>    false, //開啟緩存數(shù)據(jù)壓縮 gzcompress
        'DATA_CACHE_PATH'    =>    TMP_PATH . 'cache',
        'DATA_CACHE_KEY'    =>    '',
    )

    上面是File緩存方式的配置 關(guān)于配置項(xiàng)的更多信息

    配置名 說明
    DATA_CACHE_TYPE Apachenote、Apc、Db、Eaccelerator、File、Memcache、Redis、Shmop、Sqlite、Wincache和Xcache
    DATA_CACHE_TIME 緩存過期時(shí)間 (秒) 0 = 永久緩存
    DATA_CACHE_TABLE 如果使用數(shù)據(jù)庫DB緩存 請?zhí)顚慏B表
    DATA_CACHE_PREFIX 緩存前綴 默認(rèn)為空
    DATA_CACHE_PATH 文件緩存保存路徑 默認(rèn)為 TMP_PATH/cache
    DATA_CACHE_KEY 文件緩存名加密KEY
    DATA_CACHE_COMPRESS 是否壓縮數(shù)據(jù) (需要gzcompress , gzuncompress函數(shù)支持)
    DATA_CACHE_TIMEOUT 連接緩存服務(wù)器 超時(shí)時(shí)間 默認(rèn)為空 使用系統(tǒng)默認(rèn)值
    REDIS_HOST REDIS緩存服務(wù)器地址
    REDIS_PORT REDIS緩存服務(wù)器端口
    MEMCACHE_HOST Memcache 緩存服務(wù)器地址
    MEMCACHE_PORT Memcache 緩存服務(wù)器端口
    MEMCACHED_SERVER Memcached 緩存服務(wù)器地址 必須是array 多臺服務(wù)器IP
    MEMCACHED_LIB Memcached 配置參數(shù)

    MemcacheD 配置

    'MEMCACHED_SERVER' => array(
      array('mem1.domain.com', 11211, 33),
      array('mem2.domain.com', 11211, 67)
    );

    DB表的建立

    /**
     * 數(shù)據(jù)庫方式緩存驅(qū)動  hy_ 是你配置的數(shù)據(jù)庫前綴
     *    CREATE TABLE hy_cache (
     *      cachekey varchar(255) NOT NULL,
     *      expire int(11) NOT NULL,
     *      data blob,
     *      datacrc int(32),
     *      UNIQUE KEY `cachekey` (`cachekey`)
     *    );
     */

    換網(wǎng)線

    Cache 使用實(shí)例

    我們默認(rèn)不需要配置以上的信息, 只是有額外需求時(shí)配置. 我們的cache函數(shù)是依然可用的

    //設(shè)置緩存  設(shè)置字段user  儲存為 admin  該數(shù)據(jù)就會默認(rèn)儲存為文件  可以下次使用 
    cache('user','admin');
    
    //獲取緩存
    echo cache('user'); //獲取之前設(shè)置的user字段 
    //輸出 admin
    
    //刪除緩存
    cache('user',null) ; //將第二參數(shù)設(shè)置為null 則為刪除緩存
    
    //更多使用
    
    //設(shè)置緩存  儲存admin到user字段 有效期60秒 如果超過60秒 去獲取 user 則返回false
    cache('user','admin',array(
        'expire'=>60
    ));
    
    //設(shè)置緩存 改為 db 緩存
    cache('user','admin',array(
        'type'=>'db'
        'expire'=>60
    ));
    
    //獲取 后期db緩存
    cache('user','',array(
        'type'=>'db'
        'expire'=>60
    ));
    

    F 文件數(shù)據(jù)緩存

    F 函數(shù)是cache衍生的一個(gè)函數(shù) 他只采用File方式進(jìn)行緩存 使用方式和cache 是一致的

    //設(shè)置緩存
    F('user','admin');
    
    //輸出緩存
    echo F('user');
    
    //刪除緩存
    F('user',null)

    判斷電腦端移動端

    hy_is_mobile 函數(shù) 該函數(shù)來源于 Wordpress 中 返回(bool)

    if(hy_is_mobile())
        echo '移動短';
    else
        echo '非移動端';

    框架也直接內(nèi)置了 判斷移動端的常量 他的定義也是來源于 hy_is_mobile函數(shù) 內(nèi)置了3個(gè)常量 IS_MOBILE , IS_SHOUJI , IS_WAP

    if(IS_MOBILE)
        echo '移動端';
    else
        echo '非移動端';

    vendor 映射自動加載類路徑

    vendor 函數(shù) vendor 函數(shù)是用于自動加載類庫時(shí)使用的, 當(dāng)我們在網(wǎng)絡(luò)服務(wù)中獲得 SDK 時(shí), 就需要用到了. 現(xiàn)在大多SDK 都采用了namespace . 拿七牛云儲存的SDK演示

    在網(wǎng)站根目錄新建目錄 SDK , 在目錄中放入七牛的SDK 路徑成 wwwroot/SDK/Qiniu 當(dāng)我們的 Action 需要使用Qiniu的SDK時(shí)


    <?php
    namespace Action;
    use HY\Action;
    class Index extends Action {
        public function index(){
            $auth = new \Qiniu\Auth('accessKey', 'secretKey');
            //當(dāng)訪問時(shí) 就會出現(xiàn) 沒有\(zhòng)Qiniu\Auth 類
            //因?yàn)榭蚣懿]有找到 \Qiniu的目錄進(jìn)行自動加載
            //所以我們需要用到 vendor函數(shù)
            vendor('SDK'); 
            //意為 將 SDK 加載到自動加載路徑判斷列表中
        }
    }

    框架內(nèi)置的常量

    部分常量 你可以在框架入口文件定義它.

    常量名 說明 可否提前定義
    NOW_TIME 當(dāng)前服務(wù)器時(shí)間 返回時(shí)間戳 秒
    CLIENT_IP 當(dāng)前訪問客戶IP,非獲取真實(shí)代理!
    IS_GET 當(dāng)前訪問是否為GET
    IS_POST 當(dāng)前訪問是否為POST
    IS_AJAX 當(dāng)前訪問是否為AJAX
    ACTION_NAME 當(dāng)前訪問Action
    METHOD_NAME 當(dāng)前訪問方法函數(shù)
    IS_WAP 當(dāng)前訪問是否為移動端
    IS_SHOUJI 當(dāng)前訪問是否為移動端
    IS_MOBILE 當(dāng)前訪問是否為移動端
    PATH 項(xiàng)目路勁 Y
    ACTION_PATH Action控制器目錄路徑 Y
    VIEW_PATH View模板目錄路徑 Y
    CONF_PATH Conf配置文件目錄路徑 Y
    TMP_PATH Tmp模板緩存目錄路徑 Y
    TMPHTML_PATH TmpThml靜態(tài)緩存目錄路徑 Y
    MYLIB_PATH Lib自定義類庫目錄路徑 Y
    MODEL_PATH 模型文件目錄路徑 Y
    HY_PATH 框架目錄路徑 Y
    PLUGIN_PATH HOOK 目錄 Y
    DEBUG 調(diào)試模式 true or false Y
    PLUGIN_ON HOOK 插件機(jī)制開關(guān) (bool) Y
    PLUGIN_ON_FILE 每個(gè)插件目錄獨(dú)立開關(guān) (bool) Y
    PLUGIN_MORE_LANG_ON 中文PHP語法 (bool) Y

    ####額外說明 有的童鞋說 框架默認(rèn)生成的目錄路勁 能不能自己定義? 框架默認(rèn)會將目錄生成于根目錄下 如果你要搬走它 請把入口文件index.php改為如下:

    <?php
    define('INDEX_PATH' , str_replace('\\', '/', dirname(__FILE__)).'/');
    define('PATH' , INDEX_PATH.'Apping/');
    define('DEBUG'      ,true); 
    require INDEX_PATH . 'App/HY/HY.php';

    框架生成的目錄 就會在你的根目錄下/App目錄中生成

    框架內(nèi)置Config.php配置

    Config.php 參數(shù) 可能文檔未來得及更新 部分配置參數(shù)

    基礎(chǔ)配置

    配置項(xiàng) 說明 可否修改
    var_left_tpl { 模板變量輸出標(biāo)志符 N
    var_right_tpl } 模板變量輸出標(biāo)志符 N
    tpl_suffix 模板文件后綴 默認(rèn).html Y
    url_suffix URL為靜態(tài)后綴 默認(rèn).html Y
    url_explode 路由控制分割符號 默認(rèn)/ Y
    tmphtml_del_time 靜態(tài)文件有效期 默認(rèn)0 為永久 否則秒單位 Y
    DEBUG_PAGE DEBUG 頁面顯示 默認(rèn)false Y
    HOOK_SUFFIX HOOK后綴 Y
    error_404 404頁面模板, 默認(rèn)使用框架404頁面 Y
    MORE_LANG_LIB_FILE 額外中文PHP函數(shù)配置 (數(shù)組) Y

    數(shù)據(jù)緩存類配置

    配置項(xiàng) 說明
    DATA_CACHE_TYPE Apachenote、Apc、Db、Eaccelerator、File、Memcache、Redis、Shmop、Sqlite、Wincache和Xcache
    DATA_CACHE_TIME 緩存過期時(shí)間 (秒) 0 = 永久緩存
    DATA_CACHE_TABLE 如果使用數(shù)據(jù)庫DB緩存 請?zhí)顚慏B表
    DATA_CACHE_PREFIX 緩存前綴 默認(rèn)為空
    DATA_CACHE_PATH 文件緩存保存路徑 默認(rèn)為 TMP_PATH/cache
    DATA_CACHE_KEY 文件緩存名加密KEY
    DATA_CACHE_COMPRESS 是否壓縮數(shù)據(jù) (需要gzcompress , gzuncompress函數(shù)支持)
    DATA_CACHE_TIMEOUT 連接緩存服務(wù)器 超時(shí)時(shí)間 默認(rèn)為空 使用系統(tǒng)默認(rèn)值
    REDIS_HOST REDIS緩存服務(wù)器地址
    REDIS_PORT REDIS緩存服務(wù)器端口
    MEMCACHE_HOST Memcache 緩存服務(wù)器地址
    MEMCACHE_PORT Memcache 緩存服務(wù)器端口
    MEMCACHED_SERVER Memcached 緩存服務(wù)器地址 必須是array 多臺服務(wù)器IP
    MEMCACHED_LIB Memcached 配置參數(shù)

    數(shù)據(jù)庫配置

    配置項(xiàng) 說明
    SQL_TYPE 數(shù)據(jù)庫類型 : 數(shù)據(jù)庫引擎用了PDO, 必須開啟PDO擴(kuò)展. 數(shù)據(jù)庫支持根據(jù)你的PDO支持所支持
    SQL_NAME 數(shù)據(jù)庫庫名
    SQL_IP 數(shù)據(jù)庫 IP
    SQL_USER 數(shù)據(jù)庫 用戶名
    SQL_PASS 數(shù)據(jù)庫 密碼
    SQL_CHARSET 數(shù)據(jù)庫字符集
    SQL_PORT 數(shù)據(jù)庫 端口
    SQL_PREFIX 數(shù)據(jù)庫 前綴
    SQL_OPTION PDO配置

    插件模式

    插件模式

    什么是插件? 或者說是一種模塊 他可以在不修改你Action Model View源代碼的情況下 去修改 你的代碼內(nèi)容.
    該模式一般用于開源項(xiàng)目上使用, 可以更好的實(shí)現(xiàn)插件化程序.

    目前框架提供了兩種插件解析

    1. hook插入點(diǎn)
    2. re替換源代碼

    作者自評該模式 優(yōu)缺各有展現(xiàn), 優(yōu)點(diǎn)可以更好的模塊化, 缺點(diǎn)需要hook點(diǎn)以及關(guān)鍵字替換.

    開啟插件模式

    該模式一旦開啟 你的Action Model 將會想View一樣 采用緩存形式進(jìn)行編譯. 從而才能讓插件模式進(jìn)行解析.

    在入口文件 index.php 開啟插件模式 開發(fā)時(shí) 務(wù)必開啟 DEBUG 模式.

    <?php
    define('INDEX_PATH' , str_replace('\\', '/', dirname(__FILE__)).'/');
    define('DEBUG'      ,true); //開啟DEBUG模式
    define('PLUGIN_ON'  ,true); //開啟插件模式
    require INDEX_PATH . 'HY/HY.php';

    如果沒有這個(gè)模式需求 請不要開啟他

    新建插件

    默認(rèn)插件目錄 /Plugin. 我們在該目錄新建一個(gè)文件夾 test. 在 test 目錄下新建文件 a.hook. 在a.hook文件中寫入內(nèi)容

    echo '這是test插件的a hook內(nèi)容 <br>';

    那我們的控制器如何使用到這個(gè)a.hook呢 我們看一下控制器內(nèi)容

    <?php
        namespace Action;
        use HY\Action;
        class IndexAction extends Action {
            public function Index(){
                //{hook a}
                echo '這是Index控制器的index() 方法';
            }
        }

    訪問控制器 +++ get:/

    <<< success 這是test插件的a hook內(nèi)容 這是Index控制器的index() 方法 +++ 在控制器中建立hook點(diǎn) //{hook 名稱} 框架引擎將查找你的插件目錄 尋找到名稱.hook 吧內(nèi)容插入到控制器中執(zhí)行

    re 插件機(jī)制

    re 插件機(jī)制可以與hook同時(shí)使用, 但re機(jī)制的解析優(yōu)先級要比hook的優(yōu)先. re 插件機(jī)制 與 hook的不同之處是 hook需要在源代碼插入hook點(diǎn), 而re機(jī)制則不需要hook點(diǎn) 直接查找源代碼進(jìn)行替換修改 接著上面的做法 在test 插件目錄新建文件re.php. 寫入

    <?php
    return array(
        'Action/Index.php'=>array(
            'a1'=>'a2'
        )
    );

    上面的意思是指: 修改Action/Index.php內(nèi)容. 查找 /Plugin/test/a1 文件內(nèi)容 替換為 /Plugin/test/a2 文件內(nèi)容

    Index控制器內(nèi)容

    <?php
        namespace Action;
        use HY\Action;
        class IndexAction extends Action {
            public function Index(){
                //{hook a}
                echo '這是Index控制器的index() 方法';
            }
        }

    Plugin/test/a1 文件內(nèi)容

    echo '這是Index控制器的index() 方法';

    Plugin/test/a2 文件內(nèi)容

     echo '這是Index控制器的index() 方法 <br>';
     echo '我是re機(jī)制追加的內(nèi)容'

    訪問控制器 +++ get:/

    <<< success 這是test插件的a hook內(nèi)容 這是Index控制器的index() 方法 我是re機(jī)制追加的內(nèi)容 +++

    插件獨(dú)立開關(guān)

    控制每個(gè)插件的可用性

    入口文件增加常量定義

    <?php
    define('INDEX_PATH' , str_replace('\\', '/', dirname(__FILE__)).'/');
    define('DEBUG'      ,true); //開啟DEBUG模式
    define('PLUGIN_ON'  ,true); //開啟插件模式
    define('PLUGIN_ON_FILE',true); //插件獨(dú)立開關(guān)
    require INDEX_PATH . 'HY/HY.php';

    此時(shí)你的插件會全部失效. 只有你的插件目錄存在 on 文件 才會啟動它.

    例: test插件 /Plugin/test. 你需要在 test 目錄新建一個(gè) on 文件 (不需要寫入數(shù)據(jù)到該文件) test 插件才會生效

    中文PHP

    中文PHP 簡介

    中文PHP可以在Action Model中使用 該引擎不會與原PHP函數(shù)出現(xiàn)沖突. 目前支持大部分常用的PHP內(nèi)置函數(shù) 以及固定好的 HYPHP框架函數(shù)

    開啟 中文PHP引擎

    在入口文件 index.php 中定義常量

    define('PLUGIN_ON'  ,true);
    define('PLUGIN_MORE_LANG_ON',true);

    即可開啟該機(jī)制

    完整 index.php

    <?php
    define('DEBUG'      ,true);
    define('PLUGIN_ON'  ,true);
    define('PLUGIN_MORE_LANG_ON',true);
    require  'HY/HY.php';

    中文API

    輸出

    中文名 原PHP名稱
    輸出 echo
    輸出數(shù)組 print_r

    流程控制

    中文名 原PHP名稱
    如果 if
    或者 elseif
    反之 else
    循環(huán)對象 foreach
    循環(huán) for
    循環(huán)判斷 while
    跳出循環(huán) break
    跳到下次循環(huán) continue
    返回 return
    結(jié)束 exit
    包含文件 include
    跳轉(zhuǎn)運(yùn)行 goto
    延遲 sleep
    微秒延遲 usleep

    文件函數(shù)

    中文名 原PHP名稱
    讀取文件 file_get_contents
    寫入文件 file_put_contents
    新建目錄 mkdir
    移動文件 rename
    文件重命名 rename
    文件是否存在 is_file
    目錄是否存在 is_dir
    刪除文件 unlink
    刪除目錄 rmdir
    復(fù)制文件 copy
    打開文件 fopen
    關(guān)閉文件 fclose
    文件_指針是否結(jié)束 feof
    文件_讀取指針處字符 fgetc
    文件_讀取指針處一行 fgets
    文件_讀取指針處一行_過濾HTML fgetss
    文件_讀入數(shù)組 file
    文件_上次訪問時(shí)間 fileatime
    文件_上次修改時(shí)間 filemtime
    文件_所有者 fileowner
    文件_獲取權(quán)限 fileperms
    文件_大小 filesize
    文件_類型 filetype
    文件_鎖 flock
    文件_讀取指針處所有數(shù)據(jù) fpassthru
    文件_是否可讀 is_readable
    文件_是否可寫 is_writable

    目錄操作

    中文名 原PHP名稱
    打開目錄句柄 opendir
    關(guān)閉目錄句柄 closedir
    目錄_句柄讀取 readdir
    刪除目錄 rmdir

    系統(tǒng)程序執(zhí)行

    中文名 原PHP名稱
    執(zhí)行程序 exec
    執(zhí)行程序并返回結(jié)果 system

    數(shù)組操作函數(shù)

    中文名 原PHP名稱
    數(shù)組_索引是否存在 array_key_exists
    數(shù)組_獲取所有索引名稱 array_key_exists
    數(shù)組_合并 array_merge
    數(shù)組_排序 array_multisort
    數(shù)組_刪除結(jié)尾元素 array_pop
    數(shù)組_刪除開頭元素 array_shift
    數(shù)組_所有值相乘 array_product
    數(shù)組_所有值相加 array_sum
    數(shù)組_結(jié)尾追加元素 array_push
    數(shù)組_開頭追加元素 array_unshift
    數(shù)組_隨機(jī)取元素 array_rand
    數(shù)組_搜索值 array_search
    數(shù)組_刪除重復(fù)值 array_unique
    數(shù)組索引總數(shù) count
    數(shù)組_是否存在該值 in_array
    定義數(shù)組 array

    時(shí)間日期

    中文名 原PHP名稱
    當(dāng)前時(shí)間戳 time
    格式化時(shí)間 date

    字符串操作

    中文名 原PHP名稱
    分割字符串 explode
    分割 explode
    獲取字符串長度 strlen
    查找字符串位置 strlen
    字符串_取部分 strlen
    字符串_過濾HTML與PHP代碼 strlen
    轉(zhuǎn)為小寫 strtolower
    轉(zhuǎn)為大寫 strtoupper
    字符串_倒轉(zhuǎn) strrev
    隨機(jī)打亂字符串 str_shuffle
    字符串_首字母轉(zhuǎn)大寫 ucfirst
    字符串_買個(gè)段落首字母轉(zhuǎn)大寫 ucwords
    字符串_截?cái)鄶?shù)量 wordwrap
    字符串_引號加斜杠 addslashes
    兩個(gè)字符串相似度 similar_text

    網(wǎng)絡(luò)

    中文名 原PHP名稱
    DNS通信測試 checkdnsrr
    獲取域名指向IP gethostbyname
    獲取域名指向IP_數(shù)組 gethostbynamel
    IP轉(zhuǎn)數(shù)字 ip2long
    數(shù)字轉(zhuǎn)IP long2ip
    打開套接字 fsockopen
    打開套接字_持久 pfsockopen
    關(guān)閉套接字 fclose
    設(shè)置COOKIE setcookie

    HYPHP Action

    中文名 原PHP名稱
    輸出模板 $this->display

    HYPHP Model

    中文名 原PHP名稱
    查找 find
    插入 insert
    插入更多 insertAll
    選擇 select
    更新 update
    刪除 delete
    是否存在 has
    替換 replace
    總數(shù) count
    最大值 max
    最小值 min
    平均值 avg
    相加 sum
    調(diào)試 debug

    中文PHP 使用示例

    常規(guī)Action定義

    Index 控制器內(nèi)容

    <?php
    namespace Action;
    use HY\Action;
    class IndexAction 繼承 Action{
        公開函數(shù) index(){
            輸出 '這里是IndexAction中的Index()方法';
        }
        public function test(){
            輸出 '這里是IndexAction中的test()方法';
        }
    }

    訪問 / 則輸出

    這里是IndexAction中的Index()方法

    訪問 /index/test 則輸出

    這里是IndexAction中的test()方法

    文件操作


    Index 控制器內(nèi)容

    <?php
    namespace Action;
    use HY\Action;
    class IndexAction 繼承 Action{
        公開函數(shù) index(){
            $string = '這是一句話';
            寫入文件(PATH . 'test.txt',$string);
            輸出 讀取文件(PATH . 'test.txt');
            刪除文件(PATH . 'test.txt');
        }
    }

    寫入文件(路徑,內(nèi)容); 讀取文件(路徑); 刪除文件(路徑); 訪問輸出

    這是一句話

    更多的文件操作API 可以在文檔中查看.


    額外自定義中文解析

    你可以在 config.php 中加入配置 MORE_LANG_LIB_FILE 加入更多的中文解析配置進(jìn)來

    config.php 內(nèi)容

    <?php
    return array(
        //....其他配置
    
    
        'MORE_LANG_LIB_FILE'=>array(
                 '配置文件路徑'
        ),
    };

    例如: 在Lib目錄下新建文件 a.php; 寫入內(nèi)容

    <?php
    return array(
        '/([{};,(\s.]+)讀文件([\s\'\"\(]+)/i'=>'$1file_get_contents$2',
    };

    config.php 內(nèi)容

    <?php
    return array(
        //....其他配置
    
    
        'MORE_LANG_LIB_FILE'=>array(
                 '/Lib/a.php'
        ),
    };

    我們在代碼中就可以使用 讀文件