[ '클래스'=>'yii\db\Connection']"."/> [ '클래스'=>'yii\db\Connection']".">

 >  기사  >  PHP 프레임워크  >  yii에서 데이터베이스에 연결하는 방법

yii에서 데이터베이스에 연결하는 방법

藏色散人
藏色散人원래의
2020-01-09 10:34:162483검색

yii에서 데이터베이스에 연결하는 방법

yii에서 데이터베이스에 어떻게 연결하나요?

Yii2.0의 데이터베이스 연결에 대한 심층적인 이해

Yii는 PDO(PHP Date Object)를 사용하여 다양한 데이터베이스에 연결하므로 Yii는 거의 모든 주류 데이터베이스에 대한 우수한 지원을 제공할 수 있습니다. 이는 성숙한 프레임워크가 갖춰야 할 광범위한 적용 가능성이기도 합니다.

추천 학습: yii 프레임워크

데이터베이스에서 작업을 수행하기 전에 먼저 데이터베이스 서버와의 연결을 설정해야 합니다. Yii 애플리케이션에는 데이터베이스 연결을 처리하기 위한 전용 핵심 구성 요소가 있습니다. 구성 파일에서 쉽게 찾을 수 있습니다.

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

누군가 여기서 추측했을 것입니다. Yii는 데이터베이스 연결을 나타 내기 위해 yiidbConnection을 사용합니다. 이 연결은 PDO의 간단한 캡슐화를 구현하고, 다양한 데이터베이스 간의 차이점을 숨기고, 통합 개발 인터페이스를 구현합니다. 이러한 방식으로 프로그래밍 프로세스 중에 대부분의 데이터베이스 호환성 문제를 무시하고 기능 개발에 더 집중할 수 있습니다. 예를 들어, MySQL 등에서 Money 유형 필드를 사용할 수 없는 것에 대해 더 이상 걱정할 필요가 없습니다.

데이터베이스 스키마

Connection을 다양한 데이터베이스와 독립적으로 만들려면 데이터베이스 스키마를 언급해야 합니다. Yii는 다양한 주류 데이터베이스 스키마를 제공하며, 고유한 데이터베이스 관리 시스템(DBMS)에 맞게 자체 스키마를 작성할 수도 있습니다. 스키마와 관련된 여러 클래스가 있습니다.

yiidbSchema 추상 클래스는 다양한 DBMS의 스키마를 설명하는 데 사용됩니다.

yiidbTableSchema는 테이블 구조를 설명하는 데 사용됩니다.

yiidbColumnSchema는 필드 정보를 설명하는 데 사용됩니다.

yiidbpgsql, yiidbmysql, yiidbsqlite, yiidbmssql, yiidboci, yiidbcubird의 다양한 스키마는 다양한 DBMS를 구체적으로 설명하는 데 사용됩니다.

yiidbConnection에는 PDO 데이터베이스 드라이버와 특정 스키마 클래스 간의 매핑 관계를 설정하는 데 사용되는 $schemaMap 배열이 있습니다.

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
];

Yii는 위 배열에서 10개의 DBMS(6개 스키마)를 지원한다고 생각할 수 있습니다. default ), 대부분의 경우 이는 충분합니다. 이 범위를 넘어서 DBMS를 사용하는 경우에는 Yii가 호환성을 보장하면서 DBMS를 지원할 수 있도록 Schema를 직접 작성해 주시면 됩니다.

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()는 전체 기본 클래스에서 가장 중요한 문으로, 특정 DBMS의 하위 클래스에서 구현해야 하는 테이블의 스키마를 로드하는 함수를 정의합니다. 여기서는 yiidbmysqlSchema 하위 클래스를 예로 들어 설명합니다.

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

yiidbmysqlSchema는 먼저 매핑 관계를 정의합니다. 이 매핑 관계는 앞서 언급한 MySQL 데이터베이스의 필드 유형과 16가지 기본 데이터 유형 간의 매핑 관계입니다. 즉, MySQL Schema를 기반으로 MySQL의 필드 유형을 사용하면 통합된 16가지 기본 데이터 유형으로 변환됩니다.

테이블 정보(테이블 스키마)

yiidbTableSchema 클래스는 데이터 테이블의 정보를 기술하는 데 사용됩니다.

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

위 코드에서 yiidbTableSchema는 비교적 간단합니다. 위의 속성을 살펴보면 해당 속성이 어떤 용도로 사용되는지 대략적으로 이해할 수 있습니다. 여기를 조금 클릭해서 이해해 봅시다.

열 스키마

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

위 내용은 yii에서 데이터베이스에 연결하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:yii2 404 오류 처리다음 기사:yii2 404 오류 처리