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!

随着互联网的不断发展,Web应用程序开发的需求也越来越高。对于开发人员而言,开发应用程序需要一个稳定、高效、强大的框架,这样可以提高开发效率。Yii是一款领先的高性能PHP框架,它提供了丰富的特性和良好的性能。Yii3是Yii框架的下一代版本,它在Yii2的基础上进一步优化了性能和代码质量。在这篇文章中,我们将介绍如何使用Yii3框架来开发PHP应用程序。

随着云计算技术的不断发展,数据的备份已经成为了每个企业必须要做的事情。在这样的背景下,开发一款高可用的云备份系统尤为重要。而PHP框架Yii是一款功能强大的框架,可以帮助开发者快速构建高性能的Web应用程序。下面将介绍如何使用Yii框架开发一款高可用的云备份系统。设计数据库模型在Yii框架中,数据库模型是非常重要的一部分。因为数据备份系统需要用到很多的表和关

在当前信息时代,大数据、人工智能、云计算等技术已经成为了各大企业关注的热点。在这些技术中,显卡渲染技术作为一种高性能图形处理技术,受到了越来越多的关注。显卡渲染技术被广泛应用于游戏开发、影视特效、工程建模等领域。而对于开发者来说,选择一个适合自己项目的框架,是一个非常重要的决策。在当前的语言中,PHP是一种颇具活力的语言,一些优秀的PHP框架如Yii2、Ph

Yii框架是一个开源的PHPWeb应用程序框架,提供了众多的工具和组件,简化了Web应用程序开发的流程,其中数据查询是其中一个重要的组件之一。在Yii框架中,我们可以使用类似SQL的语法来访问数据库,从而高效地查询和操作数据。Yii框架的查询构建器主要包括以下几种类型:ActiveRecord查询、QueryBuilder查询、命令查询和原始SQL查询

随着Web应用需求的不断增长,开发者们在选择开发框架方面也越来越有选择的余地。Symfony和Yii2是两个备受欢迎的PHP框架,它们都具有强大的功能和性能,但在面对需要开发大型Web应用时,哪个框架更适合呢?接下来我们将对Symphony和Yii2进行比较分析,以帮助你更好地进行选择。基本概述Symphony是一个由PHP编写的开源Web应用框架,它是建立

yii框架:本文为大家介绍了yii将对象转化为数组或直接输出为json格式的方法,具有一定的参考价值,希望能够帮助到大家。

如果您问“Yii是什么?”查看我之前的教程:Yii框架简介,其中回顾了Yii的优点,并概述了2014年10月发布的Yii2.0的新增功能。嗯>在这个使用Yii2编程系列中,我将指导读者使用Yii2PHP框架。在今天的教程中,我将与您分享如何利用Yii的控制台功能来运行cron作业。过去,我在cron作业中使用了wget—可通过Web访问的URL来运行我的后台任务。这引发了安全问题并存在一些性能问题。虽然我在我们的启动系列安全性专题中讨论了一些减轻风险的方法,但我曾希望过渡到控制台驱动的命令

随着互联网的快速发展,Web应用越来越成为人们生活中不可或缺的一部分。而表单是Web应用中不可或缺的元素之一,其用于收集用户数据,让Web应用能够更好地为用户服务。Yii框架是一个快速、高效、灵活的PHP框架,可以帮助开发人员更加快速地开发Web应用。Yii框架中的表单构建器(FormBuilder)可以让开发人员轻松地构建复杂的表单,让Web应用具有更好


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
