[PHP] Phalcon操做示範

這篇內容將對下列操做進行示範:php

Insert、Select、Update、Calculation、Transaction、models advanced、dev-tools、cookieshtml

 

[ Insert ]git

(1)github

// 模型內操做,data是['字段'=>'值']的一維數組。

$bool = $this->save($data);

return $bool;

(2)sql

// static

$db = \Phalcon\Di::getDefault()->getShared('db');
// $db = $this->di->getShared('db');

$bool = $db->insert(
    "dianzan",
    array_values($data),  // 順序對應字段的值數組,不能含空字符串
    array_keys($data)     // 字段數組
);

return $db->lastInsertId();

(3)數組

// 批量insert

$data[] = [ 
    'site' => $v, 
    'role_id' => $role_id,
    'question_id' => $question_id,
];

$sql = \Alcon\Supports\Helper::build_insert_sql('pic_log', 'site, role_id, question_id', $data); 

$db = \Phalcon\Di::getDefault()->getShared('db');

$bool = (bool)$db->execute($sql);

return $bool;

 

[ Select ]cookie

(1)app

// 模型內操做, 參數都爲可選.

$arr = [
    // "conditions" => "question_id = 1" // 與下面直接寫條件的形式任選一種
    "status = 1 AND role_id = 3",
    "columns" => "id,isdel",
    "order" => "sort DESC, addtime DESC",
    "limit" => "2",
];

$all_res = static::find($arr)->toArray(); // 多條

$first_res = static::findFirst($arr)->toArray(); // 單條

(2)frontend

// phalcon query language

$manager = \Phalcon\Di::getDefault()->getShared('modelsManager');

$phql = "SELECT MAX(pic_status) AS pic_status FROM " . __CLASS__ . " WHERE question_id = :question_id:";

$res = $manager->executeQuery($phql, ['question_id' => $question_id])
        ->getFirst()
        ->toArray();

return $res['pic_status'];

(3)ide

// Query Builder

$builder = \Phalcon\Di::getDefault()->getShared('modelsManager')->createBuilder();

$res = $builder->columns(["MAX(" . __CLASS__ . ".pic_status)"])
        ->from(__CLASS__)
        ->where("question_id = :question_id:", ["question_id" => $question_id])
        ->getQuery()->execute()
        ->getFirst()
        ->toArray();

return reset($res);

 

[ Update ]

(1)

$db = \Phalcon\Di::getDefault()->getShared('db');
// $db = $this->di->getShared('db');

$bool = $db->update(
    'wenda_log',
    ['accept_time'],       // 字段數組
    [time()],              // 值數組,對應順序
    "id = '{$answer_id}'"  // 條件
);

return $bool;

(2)

$db = \Phalcon\Di::getDefault()->getShared('db');

$sql = "UPDATE question_log SET answer_num = answer_num + 1 WHERE question_id =  '{$question_id}'";

return (bool)$db->execute($sql);

(3)

$manager = \Phalcon\Di::getDefault()->getShared('modelsManager');

$phql = "UPDATE " . __CLASS__ . " SET iscollect = :iscollect: WHERE id = '{$id}'";

// $data = ['iscollect' => 1];
$res = $manager->executeQuery($phql, $data);

$bool = $res->success();

return $bool;

(4)

// 模型內

$this->save($data);

 

[ Calculation ]

https://docs.phalconphp.com/en/latest/reference/models.html

// 總和
return static::sum([
    'conditions' => 'xxxx',
    'column' => 'shownum',
]);

// 平均值
return static::average([
    'column' => 'shownum',
]);

// 最大
return static::maximum([
    'column' => 'shownum',
]);

// 最小
return static::minimum([
    'column' => 'shownum',
]);

// 數量

// conditions
return static::count("area='北京'");

// distinct
return static::count([
    'distinct' => 'area',
]);

 

[ Transaction ]

https://docs.phalconphp.com/en/latest/reference/model-transactions.html

$db = $di->get('db');
$db->begin();
$bool = $db->execute("INSERT ...");
if (! $bool) {
    $db->rollback();
} else {
    $bool = $db->execute("UPDATE ...");
    if (! $bool) {
        $db->rollback();
    } else {
        $db->commit();
    }
}

 

[ model advanced ]

https://docs.phalconphp.com/en/latest/reference/models-advanced.html

$di->set('otherDb', function() {});
$di->set('dbSlave', function() {});
$di->set('dbMaster', function() {});
class Exmodel extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->setConnectionService("otherDb");
    }
}
class Exmodel extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->setReadConnectionService("dbSlave");
        $this->setWriteConnectionService("dbMaster");
    }
}

https://github.com/farwish/alcon/blob/master/src/Traits/ModelTrait.php

https://github.com/farwish/alcon/blob/master/src/Traits/ModelAdvanceTrait.php

 

[ dev-tools ]

#example:

phalcon model --name=question_log --namespace=Demo\\Frontend\\Models --directory=/home/www/Demo --output=apps/frontend/models

phalcon controller --name=User --namespace=Demo\\Frontend\\Controllers --directory=/home/www/ --output=apps/frontend/controllers --base-class=ControllerBase --force

 

[ cookies ]

// This method does not removes cookies from the _COOKIE superglobal
// This method overrides any cookie set before with the same name
$this->cookies->get('name')->delete();

// Sets a cookie to be sent at the end of the request
$this->cookies->set('name', 'value', time() + $expire, '/', false, 'example.com', true);

// Sends the cookies to the client.
// Cookies aren't sent if headers are sent in the current request
$this->cookies->send();

// Check if a cookie is defined in the bag or exists in the _COOKIE superglobal
if ( $this->cookies->has('name') ) {

    // Get the cookie
    $this->cookies->get('name');

    // Get the cookie's value
    $this->cookies->get('name')->getValue();
}


// By default, cookies are automatically encrypted before being sent to the client and are decrypted when retrieved from the user. 

// Disable encryption in the following way
$di->set('cookies', function() {
    return (new \Phalcon\Http\Response\Cookies())->useEncryption(false);
});

// To use encryption, a global key must be set.
$di->set('crypt', function() {
    return (new \Phalcon\Crypt())->setKey('^YourOwnKey$');
});

 

經過查詢手冊能夠得到上述相關內容的幫助。

推薦一個用於[Phalcon]項目開發的公用庫:

https://github.com/farwish/alcon

 

Link: http://www.cnblogs.com/farwish/p/6357845.html

相關文章
相關標籤/搜索