Home PHP Framework YII How to connect to the database in yii

How to connect to the database in yii

Jan 09, 2020 am 10:34 AM
yii

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',
    ],
    // ... ...
],
// ... ...
Copy after login

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
];
Copy after login

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

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,
    ];
}
Copy after login

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 = [];           // 字段
    // ... ...
}
Copy after login

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);
    }
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP framework Yii to develop a highly available cloud backup system How to use PHP framework Yii to develop a highly available cloud backup system Jun 27, 2023 am 09:04 AM

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

Symfony vs Yii2: Which framework is better for developing large-scale web applications? Symfony vs Yii2: Which framework is better for developing large-scale web applications? Jun 19, 2023 am 10:57 AM

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

Data query in Yii framework: access data efficiently Data query in Yii framework: access data efficiently Jun 21, 2023 am 11:22 AM

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

How to use Yii3 framework in php? How to use Yii3 framework in php? May 31, 2023 pm 10:42 PM

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Jun 19, 2023 am 08:09 AM

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

Yii2 Programming Guide: How to run Cron service Yii2 Programming Guide: How to run Cron service Sep 01, 2023 pm 11:21 PM

If you're asking "What is Yii?" check out my previous tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and outlines what's new in Yii 2.0, released in October 2014. Hmm> In this Programming with Yii2 series, I will guide readers in using the Yii2PHP framework. In today's tutorial, I will share with you how to leverage Yii's console functionality to run cron jobs. In the past, I've used wget - a web-accessible URL - in a cron job to run my background tasks. This raises security concerns and has some performance issues. While I discussed some ways to mitigate the risk in our Security for Startup series, I had hoped to transition to console-driven commands

Yii2 vs Symfony: Which framework is better for API development? Yii2 vs Symfony: Which framework is better for API development? Jun 18, 2023 pm 11:00 PM

With the rapid development of the Internet, APIs have become an important way to exchange data between various applications. Therefore, it has become increasingly important to develop an API framework that is easy to maintain, efficient, and stable. When choosing an API framework, Yii2 and Symfony are two popular choices among developers. So, which one is more suitable for API development? This article will compare these two frameworks and give some conclusions. 1. Basic introduction Yii2 and Symfony are mature PHP frameworks with corresponding extensions that can be used to develop

PHP development: Use Yii2 and GrapeJS to implement back-end CMS and front-end visual editing PHP development: Use Yii2 and GrapeJS to implement back-end CMS and front-end visual editing Jun 15, 2023 pm 11:48 PM

In modern software development, building a powerful content management system (CMS) is not an easy task. Not only do developers need to have extensive skills and experience, but they also need to use the most advanced technologies and tools to optimize their functionality and performance. This article introduces how to use Yii2 and GrapeJS, two popular open source software, to implement back-end CMS and front-end visual editing. Yii2 is a popular PHPWeb framework that provides rich tools and components to quickly build

See all articles