zoukankan      html  css  js  c++  java
  • [PHP] Phalcon操作示范

    这篇内容将对下列操作进行示范:

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

    [ Insert ]

    (1)

    // 模型内操作,data是['字段'=>'值']的一维数组。
    
    $bool = $this->save($data);
    
    return $bool;

    (2)

    // static
    
    $db = PhalconDi::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 = AlconSupportsHelper::build_insert_sql('pic_log', 'site, role_id, question_id', $data); 
    
    $db = PhalconDi::getDefault()->getShared('db');
    
    $bool = (bool)$db->execute($sql);
    
    return $bool;

    [ Select ]

    (1)

    // 模型内操作, 参数都为可选.
    
    $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)

    // phalcon query language
    
    $manager = PhalconDi::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)

    // Query Builder
    
    $builder = PhalconDi::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 = PhalconDi::getDefault()->getShared('db');
    // $db = $this->di->getShared('db');
    
    $bool = $db->update(
        'wenda_log',
        ['accept_time'],       // 字段数组
        [time()],              // 值数组,对应顺序
        "id = '{$answer_id}'"  // 条件
    );
    
    return $bool;

    (2)

    $db = PhalconDi::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 = PhalconDi::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 PhalconMvcModel
    {
        public function initialize()
        {
            $this->setConnectionService("otherDb");
        }
    }
    class Exmodel extends PhalconMvcModel
    {
        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 PhalconHttpResponseCookies())->useEncryption(false);
    });
    
    // To use encryption, a global key must be set.
    $di->set('crypt', function() {
        return (new PhalconCrypt())->setKey('^YourOwnKey$');
    });

    通过查询手册可以获得上述相关内容的帮助。

    推荐一个用于[Phalcon]项目开发的公用库:

    https://github.com/farwish/alcon

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

  • 相关阅读:
    CF 444B(DZY Loves FFT-时间复杂度)
    摆弄【Nhibernate 协会制图--导乐陪伴分娩】
    固定的报文统计报告的规定
    CSS——(2)与标准流盒模型
    自动复制转换StringBuffer
    IM信息网
    Oracle Redo Log
    【转载】有哪些省时小技巧,是每个Linux用户都应该知道的
    Linux snmp
    MySQL zabbix
  • 原文地址:https://www.cnblogs.com/farwish/p/6357845.html
Copyright © 2011-2022 走看看