php 在 Slim Framework 中定义 MySQL 连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24744829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:27:09  来源:igfitidea点击:

Defining MySQL connection in Slim Framework?

phpslim

提问by itamar

I am hearing great things about Slim Framework- and it seems easy. Except none of the tutorials address where to put the MySQL info.

我听到了关于 Slim Framework 的好消息——这似乎很容易。除了没有任何教程地址放置 MySQL 信息的位置。

I see things like $dbCon = getConnection();

我看到类似的东西 $dbCon = getConnection();

But where do I define the username/pw/db/host etc?

但是我在哪里定义用户名/密码/数据库/主机等?

采纳答案by mjpramos

You can define a function in your file (e.g. index.php)

您可以在文件中定义一个函数(例如 index.php)

    function getConnection() {
    $dbhost="yourdbhost";
    $dbuser="yourdbuser";
    $dbpass="yourdbpass";
    $dbname="yourdb";
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;
    }

回答by Ivan Fretes

First thing first lets open src/settings.php file and configure database connection details to the settings array as shown below.

首先让我们打开 src/settings.php 文件并将数据库连接详细信息配置到 settings 数组,如下所示。

<?php
return [
  'settings' => [
      'displayErrorDetails' => true, // set to false in production

      // Renderer settings
      ....
      ....    

      // Monolog settings
      ....
      ....

      // Database connection settings
      "db" => [
          "host" => "localhost",
          "dbname" => "slim3",
          "user" => "root",
          "pass" => "xxxxx"
      ],
   ],
];

There are many database libraries available for PHP, but this example uses PDO. Now open your src/dependencies.php file and configure database library as shown below. you can use your own libraries by adapting the example.

有许多可用于 PHP 的数据库库,但本示例使用 PDO。现在打开您的 src/dependencies.php 文件并配置数据库库,如下所示。您可以通过修改示例来使用自己的库。

// DIC configuration
$container = $app->getContainer();

...
...
...

// PDO database library
$container['db'] = function ($c) {
    $settings = $c->get('settings')['db'];
    $pdo = new PDO("mysql:host=" . $settings['host'] . ";dbname=" . $settings['dbname'],
        $settings['user'], $settings['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    return $pdo;
};

via: https://arjunphp.com/configure-load-database-slim-framework-3/

通过:https: //arjunphp.com/configure-load-database-slim-framework-3/

回答by ForrestLyman

Its best to keep these credentials in a local configuration file. I add a configs folder outside the web root and add a local.php configuration file to that.

最好将这些凭据保存在本地配置文件中。我在 web 根目录外添加了一个 configs 文件夹,并向其中添加了一个 local.php 配置文件。

....
/configs
    local.php
/public
/vendor
....

You can configure anything you like, but here's the DB:

你可以配置任何你喜欢的东西,但这里是数据库:

<?php
// configs/local.php
return array(
    'db' => ['user' => 'root', 'password' => 'root']
);

Then include the file in your app and create the connection:

然后将文件包含在您的应用程序中并创建连接:

// public/index.php
$config = include(__DIR__ . '/../configs/local.php');
$db = new PDO("mysql:host=localhost;dbname=dbname", $config['db']['user'], $config['db']['password'] );

$app->get('/', function () use ($app, $db) {
    // do something with your db connection
});

回答by dh762

I had great success with this MVC pattern where you store the credentials in a config.phpfile which gets loaded on every instance of a model: https://github.com/revuls/SlimMVC

我在这种 MVC 模式中取得了巨大的成功,您可以将凭据存储在一个config.php文件中,该文件会加载到模型的每个实例上:https: //github.com/revuls/SlimMVC

回答by Nicolai Pefaur Zschoche

You can configure PDO in an external class:

您可以在外部类中配置 PDO:

 class Connection
    {
        protected $db;
        public function Connection()
        {
        $conn = NULL;
            try{
                $conn = new PDO("mysql:host=YOUR_HOST;dbname=DB_NAME;charset=utf8;collation=utf8_unicode_ci", "USER_DB", "PASS_DB");
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch(PDOException $e) {
                echo 'ERROR: ' . $e->getMessage();
            }   
            $this->db = $conn;
        }

        public function getConnection()
        {
            return $this->db;
        }
    }

Then in Slim (Php object oriented):

然后在 Slim (Php 面向对象) 中:

  <?php

   class Proxy
   {
    require_once 'Connection.php';

    // init Slim

    private $conn = NULL;

    // Api Rest code...


    # getConnection
    public function getConnection(){
        if(is_null($this->conn)){
            $this->conn = new Connection();
        }
        return $this->conn->getConnection();
    }

Or Php no OO:

或 PHP 没有 OO:

  <?php

    require_once 'Connection.php';

    // init Slim

    $conn = NULL;

    // Api Rest code...


    # getConnection
    function getConnection(){
        global $conn;
        if(is_null($conn)){
            $conn = new Connection();
        }
        return $conn->getConnection();
    }