yii怎么连数据库

yii怎么连数据库

yii怎么连数据库?

深入理解Yii2.0之连接数据库

Yii使用PDO(PHP Date Object)连接各种各样的数据库,因此,几乎所有主流的数据库,Yii都可以 很好地提供支持。这也是一个成熟框架所应具有的广泛适用性。

推荐学习:yii框架

在对数据库进行任何操作之前,都必须先与数据库服务器建立连接。在Yii应用中,有一个专门的核心 组件(component)用于处理数据库连接,我们很容易可以在配置文件中找到他:

'components' => [     'db' => [         'class' => 'yiidbConnection',         'dsn' => 'mysql:host=localhost;dbname=yii2advanced',         'username' => 'root',         'password' => '',         'charset' => 'utf8',     ],     // ... ... ], // ... ...

这里有人肯定已经猜到了,Yii用 yiidbConnection 来表示数据库连接。这个Connection实现了 对于PDO的一个简单封装,并掩盖了各种数据库的区别,实现了一个统一的开发接口。这样,使得你在 编程过程中,可以忽略绝大多数的数据库兼容问题,可以更加专注于功能开发。比如,你不用再担心在 MySQL下不能使用Money类型的字段等等。

数据库Schema

说到实现Connection独立于各种数据库,就不得不提到数据库Schema。Yii提供了各种主流的数据库 Schema,你甚至可以自己写一个Schema以适用自己独特的数据库管理系统(DBMS)。与Schema有关的类 有这么几个:

yiidbSchema 抽象类,用于描述各种不同的DBMS的Schema。

yiidbTableSchema 用于描述表结构。

yiidbColumnSchema 用于描述字段信息。

yiidbpgsql, yiidbmysql, yiidbsqlite, yiidbmssql, yiidboci, yiidbcubird 下的各种schema,用于具体描述各种DBMS。

在 yiidbConnection 中,有一个 $schemaMap 数组,用于建立PDO数据库驱动与具体的 schema 类间的映射关系:

public $schemaMap = [     'pgsql' => 'yiidbpgsqlSchema', // PostgreSQL     'mysqli' => 'yiidbmysqlSchema', // MySQL     'mysql' => 'yiidbmysqlSchema', // MySQL     'sqlite' => 'yiidbsqliteSchema', // sqlite 3     'sqlite2' => 'yiidbsqliteSchema', // sqlite 2     'sqlsrv' => 'yiidbmssqlSchema', // newer MSSQL driver on MS Windows hosts     'oci' => 'yiidbociSchema', // Oracle driver     'mssql' => 'yiidbmssqlSchema', // older MSSQL driver on MS Windows hosts     'dblib' => 'yiidbmssqlSchema', // dblib drivers on GNU/Linux (and maybe other OSes) hosts     'cubrid' => 'yiidbcubridSchema', // CUBRID ];

我们可以认为Yii默认情况下支持上述数组中的10种DBMS(6个Schema),这在绝大多数情况下, 是完全足够的。万一你使用了超出这一范围的DBMS,在确保兼容的情况下,你可以自己写一个Schema, 使Yii可以支持该DBMS。

Schema基类

yiidbSchema 是一个抽象类,具体的实现依赖于针对不同DBMS的6个子类Schema。擒贼先擒王, 读代码先读基类,我们就先来看看这个 yiidbSchema 吧:

abstract class Schema extends Object {     // 预定义16种基本字段类型,这16种类型是与DBMS无关的,具体到特定的DBMS时,Yii会自动     // 转换成合适的数据库字段类型。     const TYPE_PK = 'pk';     const TYPE_BIGPK = 'bigpk';     const TYPE_STRING = 'string';     const TYPE_TEXT = 'text';     const TYPE_SMALLINT = 'smallint';     const TYPE_INTEGER = 'integer';     const TYPE_BIGINT = 'bigint';     const TYPE_FLOAT = 'float';     const TYPE_DECIMAL = 'decimal';     const TYPE_DATETIME = 'datetime';     const TYPE_TIMESTAMP = 'timestamp';     const TYPE_TIME = 'time';     const TYPE_DATE = 'date';     const TYPE_BINARY = 'binary';     const TYPE_BOOLEAN = 'boolean';     const TYPE_MONEY = 'money';     // 加载表schema,需要子类具体实现     abstract protected function loadTableSchema($name);     // ... ... }

yiidbSchema 一上来就先针对各DBMS间差异最明显的字段数据类型进行统一,提供了16种基本的 字段类型。这16种类型与DBMS无关,在具体到特定的DBMS时,Yii会自动转换成合适的数据库字段类型 。我们在编程中,若需要指定字段类型,就使用这16种。这样的话,就不用考虑使用的类型具体的DBMS 是否支持的问题了。

这16种类型看着就知道是什么意思,我们就不展开讲了。

yiidbSchema::loadTableSchema() 是整个基类中最重要的一语句了,他定义了一个函数,用于 加载表的schema,需要由子类针对特定的DBMS实现。这里,我们以 yiidbmysqlSchema 子类为 例来讲解:

class Schema extends yiidbSchema {     // 定义一个数据类型的映射关系     public $typeMap = [         'tinyint' => self::TYPE_SMALLINT,         'bit' => self::TYPE_INTEGER,         'smallint' => self::TYPE_SMALLINT,         'mediumint' => self::TYPE_INTEGER,         'int' => self::TYPE_INTEGER,         'integer' => self::TYPE_INTEGER,         'bigint' => self::TYPE_BIGINT,         'float' => self::TYPE_FLOAT,         'double' => self::TYPE_FLOAT,         'real' => self::TYPE_FLOAT,         'decimal' => self::TYPE_DECIMAL,         'numeric' => self::TYPE_DECIMAL,         'tinytext' => self::TYPE_TEXT,         'mediumtext' => self::TYPE_TEXT,         'longtext' => self::TYPE_TEXT,         'longblob' => self::TYPE_BINARY,         'blob' => self::TYPE_BINARY,         'text' => self::TYPE_TEXT,         'varchar' => self::TYPE_STRING,         'string' => self::TYPE_STRING,         'char' => self::TYPE_STRING,         'datetime' => self::TYPE_DATETIME,         'year' => self::TYPE_DATE,         'date' => self::TYPE_DATE,         'time' => self::TYPE_TIME,         'timestamp' => self::TYPE_TIMESTAMP,         'enum' => self::TYPE_STRING,     ]; }

yiidbmysqlSchema 先是定义了一个映射关系,这个映射关系是MySQL数据库的字段类型与前面 我们提到的16种基本数据类型的映射关系。也就是说,基于MySQL的Schema,使用MySQL的字段类型,会 转换成统一的16种基本数据类型。

表信息(Table Schema)

yiidbTableSchema 类用于描述数据表的信息:

class TableSchema extends Object {     public $schemaName;             // 所属的Schema     public $name;                   // 表名,不包含Schema部分     public $fullName;               // 表的完整名称,可能包含一个Schema前缀。     public $primaryKey = [];        // 主键     public $sequenceName;           // 主键若使用sequence,该属性表示序列名     public $foreignKeys = [];       // 外键     public $columns = [];           // 字段     // ... ... }

从上面的代码来看, yiidbTableSchema 比较简单。上述的属性看一看就大致可以了解是干什么 用的。这里我们点一点,了解下就可以了。

列信息(Column Schema)

yiidbColumnSchema 类用于描述一个字段的信息,让我们来看一看:

class ColumnSchema extends Object {     public $name;               // 字段名     public $allowNull;          // 是否可以为NULL     /**      * @var string abstract type of this column. Possible abstract types include:      * string, text, boolean, smallint, integer, bigint, float, decimal, datetime,      * timestamp, time, date, binary, and money.      */     public $type;               // 字段的类型     /**      * @var string the PHP type of this column. Possible PHP types include:      * `string`, `boolean`, `integer`, `double`.      */     public $phpType;            // 字段类型对应的PHP数据类型     /**      * @var string the DB type of this column. Possible DB types vary according to the type of DBMS.      */     public $dbType;     public $defaultValue;       // 字段默认值     public $enumValues;         // 若字段为枚举类型,该属性用于表示可供枚举的值     /**      * @var integer display size of the column.      */     public $size;     public $precision;          // 若字段为数值,该属性用于表示精度     /**      * @var integer scale of the column data, if it is numeric.      */     public $scale;     /**      * @var boolean whether this column is a primary key      */     public $isPrimaryKey;       // 是否是主键     public $autoIncrement = false;      // 是否是自增长字段     /**      * @var boolean whether this column is unsigned. This is only meaningful      * when [[type]] is `smallint`, `integer` or `bigint`.      */     public $unsigned;           // 是否是unsigned,仅对支持的类型有效     public $comment;            // 字段描述信息     /**      * Converts the input value according to [[phpType]] after retrieval from the database.      * If the value is null or an [[Expression]], it will not be converted.      * @param mixed $value input value      * @return mixed converted value      */     public function phpTypecast($value)     {         if ($value === '' && $this->type !== Schema::TYPE_TEXT && $this->type !== Schema::TYPE_STRING && $this->type !== Schema::TYPE_BINARY) {             return null;         }         if ($value === null || gettype($value) === $this->phpType || $value instanceof Expression) {             return $value;         }         switch ($this->phpType) {             case 'resource':             case 'string':                 return is_resource($value) ? $value : (string) $value;             case 'integer':                 return (int) $value;             case 'boolean':                 return (bool) $value;             case 'double':                 return (double) $value;         }         return $value;     }     /**      * Converts the input value according to [[type]] and [[dbType]] for use in a db query.      * If the value is null or an [[Expression]], it will not be converted.      * @param mixed $value input value      * @return mixed converted value. This may also be an array containing the value as the first element      * and the PDO type as the second element.      */     public function dbTypecast($value)     {         // the default implementation does the same as casting for PHP but it should be possible         // to override this with annotation of explicit PDO type.         return $this->phpTypecast($value);     } }

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享