首頁 > php框架 > YII > 主體

yii怎麼連資料庫

藏色散人
發布: 2020-01-09 10:34:16
原創
2501 人瀏覽過

yii怎麼連資料庫

yii怎麼連資料庫?

深入理解Yii2.0之連接資料庫

Yii使用PDO(PHP Date Object)連接各種各樣的資料庫,因此,幾乎所有主流的資料庫,Yii都可以很好地提供支援。這也是一個成熟框架所應具有的廣泛適用性。

推薦學習:yii框架

在對資料庫進行任何操作之前,都必須先與資料庫伺服器建立連線。在Yii應用程式中,有一個專門的核心元件(component)用於處理資料庫連接,我們很容易可以在設定檔中找到他:

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

這裡有人肯定已經猜到了,Yii用yii\db \Connection 來表示資料庫連線。這個Connection實作了 對於PDO的一個簡單封裝,並掩蓋了各種資料庫的區別,實作了一個統一的開發介面。這樣,使得你在 程式設計過程中,可以忽略絕大多數的資料庫相容問題,可以更專注於功能開發。例如,你不用再擔心在 MySQL下不能使用Money類型的欄位等等。

資料庫Schema

說到實作Connection獨立於各種資料庫,就不得不提到資料庫Schema。 Yii提供了各種主流的資料庫 Schema,你甚至可以自己寫一個Schema以適用自己獨特的資料庫管理系統(DBMS)。與Schema有關的類別 有這麼幾個:

yii\db\Schema 抽象類,用來描述各種不同的DBMS的Schema。

yii\db\TableSchema 用來描述表結構。

yii\db\ColumnSchema 用於描述欄位資訊。

yii\db\pgsql, yii\db\mysql, yii\db\sqlite, yii\db\mssql, yii\db\oci, yii\db\cubird 下的各種schema,用於具體描述各種DBMS。

在yii\db\Connection 中,有一個$schemaMap 數組,用來建立PDO資料庫驅動與特定的schema 類別間的映射關係:

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個Schema),這在絕大多數情況下, 是完全足夠的。萬一你使用了超出這一範圍的DBMS,在確保相容的情況下,你可以自己寫一個Schema, 使Yii可以支援該DBMS。

Schema基類

yii\db\Schema 是一個抽象類,具體的實作依賴於針對不同DBMS的6個子類Schema。擒賊先擒王, 讀程式碼先讀基類,我們就先來看看這個yii\db\Schema 吧:

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 一上來就先針對各DBMS間差異最明顯的字段資料類型進行統一,提供了16種基本的字段類型。這16種類型與DBMS無關,在具體到特定的DBMS時,Yii會自動轉換成適當的資料庫欄位類型 。我們在程式設計中,若需要指定欄位類型,就使用這16種。這樣的話,就不用考慮使用的型別具體的DBMS 是否支援的問題了。

這16種類型看著就知道是什麼意思,我們就不展開講了。

yii\db\Schema::loadTableSchema() 是整個基類中最重要的一語句了,他定義了一個函數,用於加載表的schema,需要由子類針對特定的DBMS實現。這裡,我們以yii\db\mysql\Schema 子類別為例來講解:

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 先是定義了一個映射關係,這個映射關係是MySQL資料庫的欄位類型與前面我們提到的16種基本資料類型的映射關係。也就是說,基於MySQL的Schema,使用MySQL的欄位類型,會 轉換成統一的16種基本資料類型。

表格資訊(Table Schema)

yii\db\TableSchema 類別用於描述資料表的資訊:

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

從上面的程式碼來看, yii\db\TableSchema 比較簡單。上述的屬性看一看就大致可以了解是做什麼 用的。這裡我們點一點,了解下就可以了。

列資訊(Column Schema)

yii\db\ColumnSchema 類別用於描述一個欄位的訊息,讓我們來看一看:

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中文網其他相關文章!

相關標籤:
yii
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!