我无法使用 slim 版本 4 连接数据库
这是我在公共文件夹中的 index.php
当我在新数据库中单击(CTRL+左键单击)或使用 App\Models\Database 时;它在我的 db.php 文件上的我的班级数据库中是正确的
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Selective\BasePath\BasePathMiddleware;
use Slim\Factory\AppFactory;
require_once __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
// Add Slim routing middleware
$app->addRoutingMiddleware();
// Set the base path to run the app in a subdirectory.
// This path is used in urlFor().
$app->add(new BasePathMiddleware($app));
$app->addErrorMiddleware(true, true, true);
// Define app routes
$app->get('/', function (Request $request, Response $response) {
$response->getBody()->write('Hello, World!!');
return $response;
})->setName('root');
use App\Models\Database;
$app->get('/customers/all', function (Request $request, Response $response) {
$query = "SELECT * FROM customers";
try {
$db = new Database();
$conn = $db->connect();
} catch (PDOException $error) {
$error = array(
"message" => $error->getMessage()
);
$response->getBody()->write(json_encode($error));
return $response
->withHeader('Content-Type', 'applications/json')
->withStatus(500);
}
});
//customers Routes
require __DIR__ . './../routes/customers.php';
// Run app
$app->run();
这是我在配置文件夹中的 db.php 文件
<?php
namespace App\Models;
use \PDO;
class Database
{
private $host = 'localhost';
private $user = 'root';
private $pass = '';
private $dbname = 'slim-api';
public function connect()
{
$conn_str = "mysql:host=$this->host;dbname=$this->dbname";
$conn = new PDO($conn_str, $this->user, $this->pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
}
?>
我试图在 slim v4 中连接我的数据库 mysql,但我得到的是一条错误消息:找不到类“App\Models\Database”