phalcon 笔记(不定期更新)

1. model 初始化配置

public function initialize()
	{
		$this->useDynamicUpdate(true); // 动态更新字段,非全部更新
	}

2.数据库配置,记录查询sql

$di->setShared('db', function () use ($config,$di) {
    $dbConfig = $config->database->toArray();
    $adapter = $dbConfig['adapter'];
    unset($dbConfig['adapter']);

    $class = 'Phalcon\Db\Adapter\Pdo\\' . $adapter;
    /** @var Phalcon\Db\Adapter\Pdo\Mysql $connection */
    $connection =  new $class($dbConfig);
    /** @var Phalcon\Events\Manager $eventsManager */
    $eventsManager = $di->get("eventsManager");
    $logger = new \Phalcon\Logger\Adapter\File(__DIR__."/../logs/debugs.log");
    $eventsManager->attach('db', function($event, $connection) use ($logger) {
        if ($event->getType() == 'beforeQuery') {
            $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
        }
        if ($event->getType() == 'beforeSave') {
            $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO);
        }
    });
    $connection->setEventsManager($eventsManager);

    return $connection;
});

2.禁用或启用特性
https://docs.phalconphp.com/en/latest/reference/models.html#disabling-enabling-features
phalcon的orm有坑,如果数据库某个字段为null,那么update,save的时候会报错,因为phalcon默认检测字段是否Not null。
应该在model将此特性关闭。将notNullValidations设置为false

 

   public function initialize()
    {
        $this->setup(['notNullValidations'=>FALSE]);
    }

phalcon数据库配置添加表前缀

Phalcon默认居然不能设置数据表前缀,常用的框架都支持。
修改方法一:
新建一个基础模型,然后所有的模型在该类上继承即可

<?php
class BaseModel extends \Phalcon\Mvc\Model {
    public function getSource()
    {
        return 'gw_'.strtolower(get_class($this));
    }
}

但是此种方法,用phalcon devtools命令行模式生成model文件,文件名称是有表前缀的

修改方法二:
2.1 先在app/config/config.php 配置文件加上数据库前缀配置tablePrefix

    'database' => array(
        'adapter'     => 'Mysql',
        'host'        => 'localhost',
        'username'    => 'root',
        'password'    => '',
        'dbname'      => 'test',
        'charset'     => 'utf8',
        'port' => '3306',
        'tablePrefix' => 'gw_'
    ),

2.2 修改phalcon devtools
代码phalcon\devtools\scripts\Phalcon\Builder\Model.php
在220行$table = $this->options->get(‘name’);之后加上代码

$table = $this->options->get('name');
if(isset($config->database->tablePrefix)){
    $table = $config->database->tablePrefix.$table;
}

在480行
$methodRawCode[] = $this->snippet->getModelSource($this->options->get(‘name’));
修改代码为:
$methodRawCode[] = $this->snippet->getModelSource($table);

此时使用工具命令

phalcon model user

生成model :
app/models/User.php
内容如下,不会提示table不存在了:

<?php

use Phalcon\Mvc\Model\Validator\Email as Email;

class User extends \Phalcon\Mvc\Model
{

    /**
     *
     * @var integer
     */
    public $id;

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

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

    /**
     *
     * @var integer
     */
    public $status;

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

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

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

    /**
     *
     * @var integer
     */
    public $sex;

    /**
     *
     * @var integer
     */
    public $logins;

    /**
     *
     * @var integer
     */
    public $create_time;

    /**
     * Validations and business logic
     *
     * @return boolean
     */
    public function validation()
    {
        $this->validate(
            new Email(
                array(
                    'field'    => 'email',
                    'required' => true,
                )
            )
        );

        if ($this->validationHasFailed() == true) {
            return false;
        }

        return true;
    }

    /**
     * Initialize method for model.
     */
    public function initialize()
    {
        $this->setSource("gw_user");
    }

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

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return User[]
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return User
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

}