PHP-Phalcon框架中的數據庫操作


本文描述了PHP-Phalcon框架中數據庫操作方法,主要討論Phalcon框架的Model組件中的操作方法。更詳細的Model介紹請參考:官方文檔


1. 連接數據庫

在Phalcon框架中,通過在DI中注入db參數來實現數據庫的連接和配置,基本的配置方法如下:

use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;

$di->set('db', function () {
    return new DbAdapter(array(
        "host"     => "localhost",
        "username" => "root",
        "password" => "",
        "dbname"   => "test"
    ));
});

通過在$di中設置'db'的連接屬性,包括host,username,password,dbname等屬性來獲取數據庫參數,配置好db之后就可以利用Phalcon中的ORM框架了。

另一種通過配置文件的方法如下:

1.首先需要將數據信息寫入配置文件,在Phalcon中支持ini, php, json等三種配置文件形式,以下為ini形式的配置文件。

[database]
adapter  = Mysql
host     = localhost
username = root
password = 
dbname   = test

2.利用配置文件將數據庫信息寫入DI

$di->set('db', function () use ($config) {
	$config = $config->get('database')->toArray();

	$dbClass = 'Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
	unset($config['adapter']);

	return new $dbClass($config);
});

2. 建立數據庫表

在MySQL中建立數據庫表,如下所示:

CREATE TABLE `customer` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

以上語句建立了一個customer表,包括主鍵id,以及username和password兩個字段。

3. 創建模型

根據上述數據庫表,創建Customer.php模型類,需要注意的是模型類必須繼承Phalcon\MVC\Model類,並且采用與數據庫表名一致的駝峰命名法。因此建立如下的Customer類:

class Customer extends \Phalcon\Mvc\Model
{
    //采用默認的對應規則會自動映射數據庫表的字段,可以不寫
    /**
     *
     * @var integer
     */
    public $id;

    /**
     *
     * @var string
     */
    public $username;

    /**
     *
     * @var string
     */
    public $password;

    /**
     * Returns table name mapped in the model.
     *
     * @return string
     */
    public function getSource()
    {
        return 'customer';
    }
}

其實只要滿足了對應的命名規則,模型類中的屬性是不需要定義的,這里定義的目的是方便開發過程中查看,並且可以提高性能;此外,如果沒有采用數據庫表名對應的類名進行命名的話,就需要在初始化函數中通過setSource方法進行配置,配置代碼:

public function initialize()
{
    $this->setSource("tablename");
}

從這里可以看出,在現代的Web開發框架中,都遵循約定大於配置(CoC)的基本原則。只要遵循約定,就可以很方便的進行Web開發。

4. 數據庫操作

在Phalcon中操作數據庫提供了基本的ORM映射方式以及更加復雜的PHQL方式。ORM映射方式支持不寫SQL語句直接操作數據庫,基本上已經提供了絕大多數使用場景的支持;另一種更為高級的PHQL方式,支持編寫Phalcon化的SQL語句來操作數據庫。這里不編寫SQL語句,直接使用ORM映射本身提供的一切功能。


4.1 添加數據


如果我想添加一條數據,最基本的方式演示如下:

  1. 新建一個控制器DatabaseController
  2. 在控制器中添加InsertAction
  3. 在InsertAction中寫入下列代碼:
public function insertAction()
{
    $customer = new Customer();

    $customer->username = 'liyi';
    $customer->password = '123456';

    $ret = $customer->save();

    if($ret){
        print_r('插入成功');
    } else {
        print_r('插入失敗');
    }
}

4.2 查詢數據


1.find方法

Phalcon中提供了靜態方法find,采用find方法可以返回表中符合條件的所有數據:

public function findAction()
{
    $customers = Customer::find();
    $result = [];
    foreach ($customers as $customer) {
        $result[] = [
            'username' => $customer->username,
            'password' => $customer->password,
        ];
    }
    $this->response->setContentType('application/json', 'UTF-8');
    return $this->response->setJsonContent($result);
}

調用 類的靜態方法find()會返回包含有customer數據表內容的結果集,對於結果集的處理通常采用foreach進行遍歷,如代碼所示,對遍歷的每一個對象調取屬性值,然后賦值給關聯數組。

2.findFirst方法

Phalcon中的findFirst方法與find方法的使用方式幾乎無異,其區別在於findFirst方法的返回結果為單值,不需要通過foreach遍歷獲取每個值,在下面的代碼中演示了查詢數據庫表中username字段值等於'liyi'的記錄。

public function findfirstAction()
{
    $customer = Customer::findFirst("username = 'liyi'");
    $result = [
            'username' => $customer->username,
            'password' => $customer->password,
    ];
    $this->response->setContentType('application/json', 'UTF-8');
    return $this->response->setJsonContent($result);
}

3.findBy<屬性>方法

在Phalcon框架中支持findBy<屬性>的擴展查詢,在上例中,可以把條件語句改為findFirstByUsername,同時省略查詢條件,結果不變。

$customer = Customer::findFirstByUsername('kirineko');

4.參數化查詢語句

如果需要查詢的內容較多,或者是從防止SQL注入的安全角度來考慮,應當使用參數化的查詢語句。比如如果需要從數據庫中查找username=(@用戶輸入的值)並且password=(@用戶輸入的值)的用戶,那么就應當使用參數化查詢。

下面模擬用戶登錄的過程,用戶輸入用戶名和密碼,然后系統在數據庫中進行查找,如果找到則返回歡迎頁,如果沒有找到,就提示錯誤信息。

public function loginAction()
{
    $username = $this->request->getPost('username');
    $password = $this->request->getPost('password');

    $conditons = 'username = :username: and password = :password:';
    $parameters = [
        'username' => $username,
        'password' => $password,
    ];
    $ret = Customer::findFirst(
    [
        $conditons,
        'bind' => $parameters,
    ]);

    if($ret){
        print_r('login success');
    } else {
        print_r('login failed');
    }
}

4.3 更新數據


更新數據的方法通常是先查詢數據,如果能查到數據就對數據進行賦值,然后save即可。現在要更新用戶名為kirineko的密碼為用戶指定的密碼,代碼如下:

public function updateAction()
{
    $password = $this->request->getPost('password');
    $newpassword = $this->request->getPost('newpassword');

    $conditons = 'username = :username: and password = :password:';
    $parameters = [
        'username' => 'kirineko',
        'password' => $password,
    ];
    $customer = Customer::findFirst([
        $conditons,
        'bind' => $parameters,
    ]);

    if($customer){
        $customer->password = $newpassword;
        $customer->save();
        print_r('更新成功');
    } else {
        print_r('用戶名不存在或密碼錯誤');
    }
}

4.4 刪除數據


Phalcon的提供了delete命令用於刪除,現要刪除用戶名為liyi的數據,代碼如下:

public function deleteAction()
{
    $customer = Customer::findFirstByUsername('liyi');

    if($customer){
        $res = $customer->delete();
        if($res) {
            print_r('刪除成功');
        } else {
            print_r('刪除失敗');
        }
    } else {
        print_r('用戶不存在');
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM