对于加载类,我使用 PSR-4 自动加载。在我的index.php
我使用 FastRoute 组件。在那里index.php
我创建了 $db 连接并将其传递给控制器。
call_user_func_array([new $class($db), $method], $vars);
在控制器中,我收到它并将其传递给模型并在那里使用它。我知道这是不好的方法。在index.php
我如何在我的模型中使用它而不通过控制器等并且没有连接的单例实例时创建的数据库连接?如何使用 DI 或 DIC 设置数据库连接index.php
并进入所有模型?
索引.php:
<?php
require_once 'vendor/autoload.php';
$db = new DbConnection(new DbConfig($config));
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
$r->addRoute('GET', '/users', 'UserController/actionGetAllUsers');
$r->addRoute('GET', '/users/{id:\d+}', 'UserController/actionGetUserById');
});
// Fetch method and URI from somewhere
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
// Strip query string (?foo=bar) and decode URI
if (false !== $pos = strpos($uri, '?')) {
$uri = substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::NOT_FOUND:
// ... 404 Not Found
break;
case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
$allowedMethods = $routeInfo[1];
// ... 405 Method Not Allowed
break;
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
list($class, $method) = explode("/", $handler, 2);
$module = strtolower(str_replace('Controller', '', $class));
$class = 'Vendorname\\' . $module . '\\controllers\\' . $class;
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
call_user_func_array([new $class($db), $method], $vars);
break;
}
控制器:
class UserController extends BaseApiController
{
protected $db;
public function __construct($db)
{
$this->db = $db;
parent::__construct();
}
public function actionGetAllUsers()
{
$model = new User($this->db);
echo json_encode($model->getAllUsers());
}
模型:
class User
{
protected $db;
public function __construct($db)
{
$this->db = $db;
}
public function getAllUsers()
{
$stmt = $this->db->prepare('SELECT * FROM user');
$stmt->execute();
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}