【PHP】CI框架源代码DB.php(数据库类)

CI框架很少有关于数据库方面的源码分析,于是本人将数据库类的DB.php的一些见解贴出来,希望对大家有帮助:
<!--?php
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014 - 2016, British Columbia Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package    CodeIgniter
 * @author    EllisLab Dev Team
 * @copyright    Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
 * @copyright    Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/)
 * @license    http://opensource.org/licenses/MIT    MIT License
 * @link    https://codeigniter.com
 * @since    Version 1.0.0
 * @filesource
 */
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 *初始化数据库
 * Initialize the database
 *
 * @category    Database
 * @author    EllisLab Dev Team
 * @link    https://codeigniter.com/user_guide/database/
 *
 * @param     string|string[]    $params
 * @param     bool        $query_builder_override
 *                Determines if query builder should be used or not
 */
function &DB($params = '', $query_builder_override = NULL)
{
    // Load the DB config file if a DSN string wasn't passed
    //如果DSN没通过,则load 配置文件
    if (is_string($params) && strpos($params, '://') === FALSE)
    {
        // Is the config file in the environment folder?
        if ( ! file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/database.php')
            && ! file_exists($file_path = APPPATH.'config/database.php'))
        {
            show_error('The configuration file database.php does not exist.');
        }
        //加载配置文件
        include($file_path);

        // Make packages contain database config files,
        // given that the controller instance already exists
        //查看包中是否时候有config/database.php这文件,如果有,则加载
        if (class_exists('CI_Controller', FALSE))
        {
            //加载包,格式在APPPATH的config目录中定义,格式如下:
            //$autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
            //get_package_paths()为CI_Loader::get_package_paths()
            foreach (get_instance()->load->get_package_paths() as $path)
            {
                if ($path !== APPPATH)
                {
                    if (file_exists($file_path = $path.'config/'.ENVIRONMENT.'/database.php'))
                    {
                        include($file_path);
                    }
                    elseif (file_exists($file_path = $path.'config/database.php'))
                    {
                        include($file_path);
                    }
                }
            }
        }
        //$db为config/database.php中的配置变量
        if ( ! isset($db) OR count($db) === 0)
        {
            show_error('No database connection settings were found in the database config file.');
        }

        if ($params !== '')
        {
            $active_group = $params;
        }
        //$active_group没有设置,则说明没有数据库连接
        if ( ! isset($active_group))
        {
            show_error('You have not specified a database connection group via $active_group in your config/database.php file.');
        }
        //$db[$active_group]为空,说明指定一个无效的数据库连接组,默认为$db['default']
        elseif ( ! isset($db[$active_group]))
        {
            show_error('You have specified an invalid database connection group ('.$active_group.') in your config/database.php file.');
        }
        //参数为配置文件中指定的数组,默认为$db['default']
        $params = $db[$active_group];
    }
    elseif (is_string($params))
    {
        /**
         * Parse the URL from the DSN string
         * Database settings can be passed as discreet
         * parameters or as a data source name in the first
         * parameter. DSNs must have this prototype:
         * $dsn = 'driver://username:password@hostname/database';
         * 完整是这样
         * driver://username:password@hostname/database?option1=value1&option2=value2..
         */
        if (($dsn = @parse_url($params)) === FALSE)
        {
            show_error('Invalid DB Connection String');
        }

        $params = array(
            'dbdriver'    => $dsn['scheme'],
            'hostname'    => isset($dsn['host']) ? rawurldecode($dsn['host']) : '',
            'port'        => isset($dsn['port']) ? rawurldecode($dsn['port']) : '',
            'username'    => isset($dsn['user']) ? rawurldecode($dsn['user']) : '',
            'password'    => isset($dsn['pass']) ? rawurldecode($dsn['pass']) : '',
            'database'    => isset($dsn['path']) ? rawurldecode(substr($dsn['path'], 1)) : ''
        );

        // Were additional config items set?
        // 是否有附加的配置项
        if (isset($dsn['query']))
        {
            //将dsn的查询string解析到数组$extra
            parse_str($dsn['query'], $extra);

            foreach ($extra as $key => $val)
            {
                if (is_string($val) && in_array(strtoupper($val), array('TRUE', 'FALSE', 'NULL')))
                {
                    $val = var_export($val, TRUE);
                }

                $params[$key] = $val;
            }
        }
    }

    // No DB specified yet? Beat them senseless...
    //db没有选择,show error
    if (empty($params['dbdriver']))
    {
        show_error('You have not selected a database type to connect to.');
    }

    // Load the DB classes. Note: Since the query builder class is optional
    // we need to dynamically create a class that extends proper parent class
    // based on whether we're using the query builder class or not.
    if ($query_builder_override !== NULL)
    {
        $query_builder = $query_builder_override;
    }
    // Backwards compatibility work-around for keeping the
    // $active_record config variable working. Should be
    // removed in v3.1
    //$active_record
    //没有定义查询构造器并且$active_record被设置
    //$active_record=TRUE,可以放入配置文件中(database.php)
    //所谓的查询构造器$user = DB::table('users')->where('name', 'John')->first();以这种方式进行访问
    elseif ( ! isset($query_builder) && isset($active_record))
    {
        $query_builder = $active_record;
    }
    //包含CI_DB_driver类(抽象类)
    require_once(BASEPATH.'database/DB_driver.php');

    if ( ! isset($query_builder) OR $query_builder === TRUE)
    {
        //包含CI_DB_query_builder类
        require_once(BASEPATH.'database/DB_query_builder.php');
        if ( ! class_exists('CI_DB', FALSE))
        {
            /**
            *默认和$query_builder===TRUE时,继承CI_DB_query_builder { },否则继承CI_DB_driver { }
            * CI_DB
             *
             *扮演CI_DB_driver和CI_DB_query_builder的别名
             * Acts as an alias for both CI_DB_driver and CI_DB_query_builder.
             *
             *
             * @see    CI_DB_query_builder
             * @see    CI_DB_driver
             */
            class CI_DB extends CI_DB_query_builder { }
        }
    }
    elseif ( ! class_exists('CI_DB', FALSE))
    {
        /**
          * @ignore
         */
        class CI_DB extends CI_DB_driver { }
    }

    // Load the DB driver
    $driver_file = BASEPATH.'database/drivers/'.$params['dbdriver'].'/'.$params['dbdriver'].'_driver.php';

    //不存在驱动文件,则报错
    file_exists($driver_file) OR show_error('Invalid DB driver');
    require_once($driver_file);

    // Instantiate the DB adapter
    //实例化DB适配器,如果是mysql,$driver为CI_DB_mysql_driver ,继承自上面的CI_DB
    //继承关系:'CI_DB_'.$params['dbdriver'].'_driver' extends CI_DB extends CI_DB_driver(或者CI_DB_query_builders)
    $driver = 'CI_DB_'.$params['dbdriver'].'_driver';
    $DB = new $driver($params);

    // Check for a subdriver
    //查看是否有子驱动
    if ( ! empty($DB->subdriver))
    {
        $driver_file = BASEPATH.'database/drivers/'.$DB->dbdriver.'/subdrivers/'.$DB->dbdriver.'_'.$DB->subdriver.'_driver.php';

        if (file_exists($driver_file))
        {
            require_once($driver_file);
            $driver = 'CI_DB_'.$DB->dbdriver.'_'.$DB->subdriver.'_driver';
            //实例化子驱动
            $DB = new $driver($params);
        }
    }
    //初始化数据库设置,包含建立连接以及设置客户端字符集
    $DB->initialize();
    //返回DB实例
    return $DB;
}

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30221425/viewspace-2095310/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/30221425/viewspace-2095310/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在CodeIgniter框架中实现数据库部分数据加密方法,可以使用框架自带的加密 `Encryption`。 以下是一个简单的实现示例: ```php class MY_Model extends CI_Model { protected $table_name = ''; protected $primary_key = ''; protected $encrypt_fields = array(); public function __construct() { parent::__construct(); $this->load->library('encryption'); } public function get($id) { $this->db->where($this->primary_key, $id); $query = $this->db->get($this->table_name); $row = $query->row_array(); foreach ($this->encrypt_fields as $field) { $row[$field] = $this->encryption->decrypt($row[$field]); } return $row; } public function insert($data) { foreach ($this->encrypt_fields as $field) { $data[$field] = $this->encryption->encrypt($data[$field]); } return $this->db->insert($this->table_name, $data); } public function update($id, $data) { foreach ($this->encrypt_fields as $field) { $data[$field] = $this->encryption->encrypt($data[$field]); } $this->db->where($this->primary_key, $id); return $this->db->update($this->table_name, $data); } } ``` 在这个示例中,我们创建了一个 `MY_Model` ,它继承自 CodeIgniter 框架的 `CI_Model` 。在构造函数中,我们加载了框架自带的加密 `Encryption`。 我们定义了三个属性,分别为数据库表名 `$table_name`、主键名 `$primary_key`,以及需要加密的字段名数组 `$encrypt_fields`。 我们提供了三个方法,分别为 `get`、`insert`、`update`,用于获取、插入、更新数据。在 `get` 方法中,我们查询数据库并获取一行数据,然后遍历 `$encrypt_fields` 数组,对每个需要加密的字段调用 `encryption` 的 `decrypt` 方法进行解密。在 `insert` 和 `update` 方法中,我们同样遍历 `$encrypt_fields` 数组,对每个需要加密的字段调用 `encryption` 的 `encrypt` 方法进行加密。最后,我们调用框架自带的数据库操作方法 `insert` 和 `update` 进行插入和更新操作。 这样,我们就可以在 CodeIgniter 框架中方便地实现数据库部分数据加密了。当然,这只是一个简单的示例,实际应用中还需要考虑很多其他因素,例如密钥的管理、加密算法的选择等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值