我听说Slim Framework很棒 - 看起来很简单。除非这些教程都没有解决MySQL信息的放置位置。
我看到$dbCon = getConnection();
但是我在哪里定义用户名/ pw / db / host等?
答案 0 :(得分:5)
首先让我们打开src / settings.php文件,并将数据库连接详细信息配置到设置数组,如下所示。
<?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"
],
],
];
有许多可用于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/
答案 1 :(得分:4)
您可以在文件中定义一个函数(例如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;
}
答案 2 :(得分:4)
最好将这些凭据保存在本地配置文件中。我在Web根目录外添加一个configs文件夹,并为其添加一个local.php配置文件。
....
/configs
local.php
/public
/vendor
....
您可以配置任何您喜欢的内容,但这里是数据库:
<?php
// configs/local.php
return array(
'db' => ['user' => 'root', 'password' => 'root']
);
然后在您的应用中包含该文件并创建连接:
// 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
});
答案 3 :(得分:2)
我使用此MVC模式取得了巨大成功,您将凭据存储在config.php
文件中,该文件将加载到模型的每个实例上:https://github.com/revuls/SlimMVC
答案 4 :(得分:1)
您可以在外部类中配置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;
}
}
然后在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();
}
或Php no 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();
}