RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 709614
Accepted
fosh4455
fosh4455
Asked:2020-08-23 21:55:00 +0000 UTC2020-08-23 21:55:00 +0000 UTC 2020-08-23 21:55:00 +0000 UTC

如何将连接参数传递给 DB 类?[关闭]

  • 772
关闭。这个问题不可能给出客观的答案。目前不接受回复。

想改进这个问题? 重新构建问题,以便可以根据事实和引用来回答。

5年前关闭。

改进问题
class DB
{
    // объявление свойств
    protected $host = 'localhost';
    protected $db =   'db';
    protected $charset = 'utf8';
    protected $user = 'user';
    protected $pass = 'pwd';

    public function __construct() {
        // создание подключения к БД
    }

    // другие методы класса
}

传递我拥有的参数的选项:

  1. 像示例中那样直接在课堂上写(他们说不是犹太洁食)
  2. 我个人不喜欢在创建类的实例时传递这个方法$db = new DB($host, $db, $charset ...);,我每次都需要不断地传递所有变量,最重要的是:从哪里得到传递?来自全球?
  3. 放入配置。让我们承认。如何绕过全局将配置传递给类?
  4. ... ?
php
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. dpi
    2020-08-24T01:16:58Z2020-08-24T01:16:58Z

    您解析的一个 ini 文件

    $config = **parse_ini_file**('config.ini', true);
    
    // define DB configuration
    $configDb = $config['db'];
    define('DB_HOST', $configDb['host']);
    define('DB_USER', $configDb['user']);
    define('DB_PASSWORD', $configDb['password']);
    define('DB_NAME', $configDb['dbname']);
    define('DB_PORT', $configDb['port']);
    

    好吧,您为自己创建一个连接常量的类))

    $link = new mysqli(DB_HOST, DB_USER, DB_PASSWORD);
    

    然后,您只需执行自动加载,将所有内容(所有类,所有存储常量的所有文件)都放入其中。

    这是一个单独的配置文件。您连接到所有页面。

     require_once 'config.php';
     require_once 'DB.php';
    

    嗯,一般来说,使用 PDO 更好——它不仅连接到 MySQL,而且连接到许多数据库。

    • 1
  2. Best Answer
    paqstd
    2020-08-24T00:55:37Z2020-08-24T00:55:37Z

    数据库连接类

    namespace Engine\Core\Database;
    
    use \PDO;
    use Engine\Core\Config\Config;
    class Connection
        {
            private $link;
    
            /**
             * Connection constructor.
             */
            public function __construct()
            {
                $this->connect();
            }
    
            /**
             * @return $this
             */
            private function connect()
            {
                $config = Config::file('database');
    
                $dsn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['db_name'] . ';charset=' . $config['charset'];
    
                $this->link = new PDO($dsn, $config['username'], $config['password']);
    
                return $this;
    
            }
            /**
             * @param $sql
             * @param array $values
             * @return mixed
             */
            public function execute($sql, $values = [])
            {
                $sth = $this->link->prepare($sql);
                return $sth->execute($values);
            }
            /**
             * @param $sql
             * @param array $values
             * @return array
             */
            public function query($sql, $values = [])
            {
    
                $sth = $this->link->prepare($sql);
    
                $sth->execute($values);
                $result = $sth->fetchAll(PDO::FETCH_ASSOC);
                if ($result === false) {
                    return [];
                }
    
                return $result;
            }
        }
    

    queryBuilder 类 - 请注意。

    namespace Engine\Core\Database;
    class QueryBuilder
    {
        /**
         * @var array
         */
        protected $sql = [];
        /**
         * @var array
         */
        public $values = [];
    
        /**
         * @param string $fields
         * @return $this
         */
        public function select($fields = '*')
        {
            $this->reset();
            $this->sql['select'] = "SELECT {$fields} ";
    
            return $this;
        }
    
        /**
         * @param $table
         * @return $this
         */
        public function from($table)
        {
            $this->sql['from'] = "FROM {$table} ";
    
            return $this;
        }
    
        /**
         * @param $column
         * @param $value
         * @param string $operator
         * @return $this
         */
        public function where($column, $value, $operator = '=')
        {
            $this->sql['where'][] = "{$column} {$operator} ?";
            $this->values[] = $value;
    
            return $this;
        }
    
        /**
         * @param $field
         * @param $order
         * @return $this
         */
        public function orderBy($field, $order)
        {
            $this->sql['order_by'] = " ORDER BY {$field} {$order}";
    
            return $this;
        }
    
        /**
         * @param $number
         * @return $this
         */
        public function limit($number)
        {
            $this->sql['limit'] = " LIMIT {$number}";
    
            return $this;
        }
    
        public function update($table)
        {
            $this->reset();
            $this->sql['update'] = " UPDATE {$table} ";
    
            return $this;
        }
    
        public function insert($table)
        {
            $this->reset();
            $this->sql['insert'] = "INSERT INTO {$table} ";
    
            return $this;
        }
    
        public function set($data = [])
        {
            $this->sql['set'] .= " SET ";
    
            if (!empty($data)) {
                foreach ($data as $key => $value) {
                    $this->sql['set'] .= "{$key} = ?";
                    if (next($data)) {
                        $this->sql['set'] .= ", ";
                    }
                    $this->values[] = $value;
                }
            }
            return $this;
        }
    
        /**
         * @return string
         */
        public function sql()
        {
            $sql = '';
            if (!empty($this->sql)) {
                foreach ($this->sql as $key => $value) {
                    if ($key == 'where') {
                        $sql .= " WHERE ";
                        foreach ($value as $where) {
                            $sql .= $where;
                            if (count($value) > 1 and next($value)) {
                                $sql .= ' AND ';
                            }
                        }
                    } else {
                        $sql .= $value;
                    }
                }
            }
            return $sql;
        }
    
        public function reset()
        {
            $this->sql = [];
            $this->values = [];
        }
    
    }
    

    然后,如有必要,只需调用代码

    $this->db->execute(
                    $this->queryBuilder->update($this->getTable())
                        ->set($properties)
                        ->where('id', $this->id)
                        ->sql(),
                    $this->queryBuilder->values
                    );
    

    我在我的网站上使用了这个模式,我认为它对你有用。顺便说一下,如果你想使用 DI

    namespace Engine;
    use Engine\DI\DI;
    
    abstract class Controller
    {
        /**
         * @var DI
         */
        protected $di;
        protected $db;
    
    
        /**
         * Controller constructor.
         * @param DI $di
         */
        public function __construct(DI $di)
        {
            $this->di       = $di;
            $this->db       = $this->di->get('db');
    
        }
    }
    


    这是其他文件(配置)

    namespace Engine\Core\Config;
    class Config
    {
        /**
         * @param $key
         * @param string $group
         * @return null
         */
        public static function item($key, $group = 'main')
        {
            $groupItems = static::file($group);
            return isset($groupItems[$key]) ? $groupItems[$key] : null;
        }
    
        /**
         * @param $group
         * @return bool|mixed
         * @throws \Exception
         */
        public static function file($group)
        {
            $path = $_SERVER['DOCUMENT_ROOT'] . '/' .  mb_strtolower(ENV) . '/Config/' . $group . '.php';
    
            if(file_exists($path))
            {
                $items = require_once $path;
    
                if(!empty($items))
                {
                    return $items;
                }
                else
                {
                    throw new \Exception(
                        sprintf(
                            'Config file <b>%s</b> is not a valid array.', $path
                        )
                    );
                }
            }
            else
            {
                throw new \Exception(
                    sprintf('Cannot load config from file, file <b>%s</b> does not exist.', $path)
                );
            }
    
            return false;
        }
    }
    

    如果代码中有不清楚的地方,请写在注释中。

    • 0

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    Python 3.6 - 安装 MySQL (Windows)

    • 1 个回答
  • Marko Smith

    C++ 编写程序“计算单个岛屿”。填充一个二维数组 12x12 0 和 1

    • 2 个回答
  • Marko Smith

    返回指针的函数

    • 1 个回答
  • Marko Smith

    我使用 django 管理面板添加图像,但它没有显示

    • 1 个回答
  • Marko Smith

    这些条目是什么意思,它们的完整等效项是什么样的

    • 2 个回答
  • Marko Smith

    浏览器仍然缓存文件数据

    • 1 个回答
  • Marko Smith

    在 Excel VBA 中激活工作表的问题

    • 3 个回答
  • Marko Smith

    为什么内置类型中包含复数而小数不包含?

    • 2 个回答
  • Marko Smith

    获得唯一途径

    • 3 个回答
  • Marko Smith

    告诉我一个像幻灯片一样创建滚动的库

    • 1 个回答
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Алексей Шиманский 如何以及通过什么方式来查找 Javascript 代码中的错误? 2020-08-03 00:21:37 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    user207618 Codegolf——组合选择算法的实现 2020-10-23 18:46:29 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5