Phalcon - 查詢語言



Phalcon 查詢語言 (PHQL),也稱為PhalconQL,是一種高階 SQL 方言,它標準化了 Phalcon 支援的資料庫系統的 SQL 查詢。

它包含一個用 C 編寫的解析器,用於將語法轉換為目標 RDBMS。

以下是 Phalcon 查詢語言的一些主要功能列表:

  • 為了 Web 應用的安全,它使用繫結引數。

  • 表被視為模型,而列被視為類屬性。

  • 所有資料操作語句都用於防止可能發生的資料丟失。

  • 透過一次保持一個 SQL 查詢呼叫來防止 SQL 注入。

建立 PHQL 查詢

透過例項化類Phalcon\Mvc\Model\Query來建立查詢。

示例

// Instantiate the Query 
$query = new Query( 
   "SELECT * FROM Users", 
   $this->getDI() 
);  

// Execute the query returning a result if any 
$cars = $query->execute(); 

在前面的章節中,我們已經看到了名為部落格教程的腳手架 Web 應用的工作原理。它包括根據名稱或 slug 搜尋類別。

以下是 searchAction 中包含的程式碼。

public function searchAction() {  
   $numberPage = 1; 
   if ($this->request->isPost()) { 
      $query = Criteria::fromInput($this->di, "Categories", $_POST); 
      $this->session->conditions = $query->getConditions(); 
   } else { 
      $numberPage = $this->request->getQuery("page", "int"); 
      if ($numberPage <= 0) { 
         $numberPage = 1; 
      } 
   } 
   
   $parameters = array(); 
   if ($this->session->conditions) { 
      $parameters["conditions"] = $this->session->conditions; 
   } 
   
   // $parameters["order"] = "id"; 
   $categories = Categories::find($parameters); 
   if (count($categories) == 0) { 
      $this->flash->notice("The search did not find any categories"); 
      
      return $this->dispatcher->forward(array( 
         "controller" => "categories", 
         "action" => "index" 
      )); 
   } 
   
   $paginator = new \Phalcon\Paginator\Adapter\Model(array( 
      "data" => $categories, 
      "limit"=> 10, 
      "page" => $numberPage 
   )); 
   
   $page = $paginator->getPaginate(); 
   $this->view->setVar("page", $page); 
}

控制器中執行的 PHQL 查詢(已突出顯示)將根據搜尋條件獲取所有結果。任何根據條件的搜尋查詢的結果都將如螢幕截圖所示顯示。

以下是上述程式碼成功執行後收到的輸出。

PHQL

PHQL 生命週期

作為一種高階語言,PHQL 使開發人員能夠根據需求個性化和定製各個方面。

以下是每個在 Phalcon 中執行的 PHQL 語句的生命週期:

  • 每個 PHQL 語句都被解析並轉換為中間表示 (IR),它完全獨立於資料庫系統實現的 SQL。

  • IR 會根據 Web 應用中使用的資料庫系統轉換為 SQL 語句。生成的 SQL 語句與模型相關聯。

  • 所有 PHQL 語句都會被解析一次並快取在記憶體中。如果執行相同的語句結果,它將有助於提高效能。

Life Cycle
廣告

© . All rights reserved.