['class'=>'yii\ db\Connection']"."/> ['class'=>'yii\ db\Connection']".">

Home>Article>PHP Framework> How to connect to the database in yii

How to connect to the database in yii

藏色散人
藏色散人 Original
2020-01-09 10:34:16 2455browse

How to connect to the database in yii

How does yii connect to the database?

In-depth understanding of connecting to the database in Yii2.0

Yii uses PDO (PHP Date Object) to connect to a variety of databases, therefore, almost all mainstream Yii can provide good support for any database. This is also the broad applicability that a mature framework should have.

Recommended learning:yii framework

Before performing any operation on the database, a connection must be established with the database server. In the Yii application, there is a dedicated core component for handling database connections. We can easily find it in the configuration file:

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

Someone must have guessed here, Yii uses yii\db \Connection to represent a database connection. This Connection implements a simple encapsulation of PDO, masks the differences between various databases, and implements a unified development interface. In this way, you can ignore most database compatibility issues during the programming process and focus more on functional development. For example, you no longer have to worry about not being able to use Money type fields under MySQL, etc.

Database Schema

When it comes to realizing that Connection is independent of various databases, we have to mention database Schema. Yii provides various mainstream database schemas, and you can even write your own schema to suit your own unique database management system (DBMS). There are several classes related to Schema:

yii\db\Schema abstract class, used to describe the Schema of various DBMSs.

yii\db\TableSchema is used to describe the table structure.

yii\db\ColumnSchema is used to describe field information.

Various schemas under yii\db\pgsql, yii\db\mysql, yii\db\sqlite, yii\db\mssql, yii\db\oci, yii\db\cubird, for specific Describe various DBMS.

In yii\db\Connection, there is a $schemaMap array, which is used to establish the mapping relationship between the PDO database driver and the specific schema class:

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

We can think that Yii defaults to It supports 10 DBMSs (6 Schemas) in the above array, which is completely sufficient in most cases. In case you use a DBMS beyond this range, you can write a Schema yourself so that Yii can support the DBMS while ensuring compatibility.

Schema base class

yii\db\Schema is an abstract class, and the specific implementation depends on 6 subclasses of Schema for different DBMS. To catch the thief first, catch the king first. When reading the code, read the base class first. Let’s take a look at this yii\db\Schema first:

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); // ... ... }

yii\db\Schema. At the beginning, we will focus on the most obvious differences between DBMS. The field data types are unified and 16 basic field types are provided. These 16 types have nothing to do with DBMS. When it comes to a specific DBMS, Yii will automatically convert it into the appropriate database field type. In programming, if we need to specify field types, we use these 16 types. In this case, there is no need to consider whether the specific DBMS used supports it.

You will know what these 16 types mean just by looking at them, so we won’t go into details.

yii\db\Schema::loadTableSchema() is the most important statement in the entire base class. It defines a function for loading the schema of the table, which needs to be implemented by a subclass for a specific DBMS. . Here, we take the yii\db\mysql\Schema subclass as an example to explain:

class Schema extends \yii\db\Schema { // 定义一个数据类型的映射关系 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, ]; }

yii\db\mysql\Schema first defines a mapping relationship. This mapping relationship is the field type of the MySQL database and the previous The mapping relationships of the 16 basic data types we mentioned. In other words, based on MySQL Schema, using MySQL field types will be converted into unified 16 basic data types.

Table information (Table Schema)

yii\db\TableSchema class is used to describe the information of the data table:

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

From the above code See, yii\db\TableSchema is relatively simple. You can roughly understand what they are used for by taking a look at the above attributes. Let’s click a little bit here to understand it.

Column information (Column Schema)

yii\db\ColumnSchema class is used to describe the information of a field, let us take a look:

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 above is the detailed content of How to connect to the database in yii. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:yii2 404 error handling Next article:yii2 404 error handling