如何使用PHP DI加载数据库容器?这是迄今为止我尝试过的变体之一。
设置.php
<?php
use MyApp\Core\Database;
use MyApp\Models\SystemUser;
return [
'Database' => new Database(),
'SystemUser' => new SystemUser()
];
初始化文件
$containerBuilder = new \DI\ContainerBuilder();
$containerBuilder->addDefinitions('Settings.php');
$container = $containerBuilder->build();
SystemUserDetails.php
<?php
namespace MyApp\Models\SystemUser;
use MyApp\Core\Database;
use MyApp\Core\Config;
use MyApp\Helpers\Session;
/**
*
* System User Details Class
*
*/
class SystemUserDetails
{
/*=================================
= Variables =
=================================*/
private $db;
/*===============================
= Methods =
================================*/
/**
*
* Construct
*
*/
public function __construct(Database $db)
{
# Get database instance
// $this->db = Database::getInstance();
$this->db = $db;
}
/**
MyApp\Models\SystemUser\SystemUserDetails::__construct() 函数的参数太少,在第 54 行的 /www/myapp/models/SystemUser.php 中传递了 0,而预期的文件正好是 1 文件:/www/myapp/models/SystemUser/SystemUserDetails .php
数据库不应该自动加载吗?
痕迹:
目前,我的主
index.php
文件扩展init.php
了它创建容器的文件(在帖子中粘贴了代码部分)。然后我调用
App
类,它获取 URL(mysite.com/login/user_login) 并实例化一个新的控制器类并运行上述方法,在这种情况下,它是第一页 -MyApp/Contollers/Login.php
。- 该
user_login
方法获取凭据,验证它们,如果它们有效,则使用 SystemUser 对象登录。
- 该
系统用户类:
namespace MyApp\Models;
class SystemUser
{
public $id;
# @obj SystemUser profile information (fullname, email, last_login, profile picture, etc')
protected $systemUserDetatils;
public function __construct($systemUserId = NULL)
{
# Create systemUserDedatils obj
$this->systemUserDetatils = new \MyApp\Models\SystemUser\SystemUserDetails();
# If system_user passed
if ( $systemUserId ) {
# Set system user ID
$this->id = $systemUserId;
# Get SysUser data
$this->systemUserDetatils->get($this);
} else {
# Check for sysUser id in the session:
$systemUserId = $this->systemUserDetatils->getUserFromSession();
# Get user data from session
if ( $systemUserId ) {
# Set system user ID
$this->id = $systemUserId;
# Get SysUser data
$this->systemUserDetatils->get($this);
}
}
}
}