问题描述
如何使用 PHP DI 加载数据库容器?这是我到目前为止尝试的变体之一.
How do I load a database container using PHP DI?This is one of the variations I have tried up until now.
Settings.php
Settings.php
<?php
use MyApp\Core\Database;
use MyApp\Models\SystemUser;
return [
'Database' => new Database(),
'SystemUser' => new SystemUser()
];
init.php
$containerBuilder = new \DI\ContainerBuilder();
$containerBuilder->addDefinitions('Settings.php');
$container = $containerBuilder->build();
SystemUserDetails.php
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;
}
/**
数据库不会自动加载吗?
Shouldn't the database get loaded automatically?
踪迹:
-
目前,我的主
index.php
文件扩展了init.php
,这是它创建容器的文件(文章中粘贴的代码部分).
Currrently, My main
index.php
file extendsinit.php
which is the file where it create the container (pasted code part in the post).
然后我调用App
类,该类将获取URL(mysite.com/login/user_login)并实例化一个新的控制器类并运行所提到的方法,在这种情况下,它是第一页-MyApp/Contollers/Login.php
.
Then I call the App
class, which fetches the URL(mysite.com/login/user_login) and instantiate a new controller class and run the mentioned method, in this case, it's the first page - MyApp/Contollers/Login.php
.
-
user_login
方法获取凭据,对其进行验证,如果它们有效,则使用SystemUser对象进行登录.
- The
user_login
method fetches the credentials, validate them, and if they are valid, uses the SystemUser object to login.
SystemUser类:
SystemUser class:
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);
}
}
}
}
推荐答案
PHP-DI正常工作.
PHP-DI is working correctly.
在您的SystemUser
课堂上,您正在做
In your SystemUser
class you are doing:
$this->systemUserDetatils = new \MyApp\Models\SystemUser\SystemUserDetails();
SystemUserDetails
的构造函数需要一个您未传递的Database
对象.
The constructor for SystemUserDetails
requires a Database
object, which you are not passing.
通过直接调用new
,您没有使用PHP-DI .通过这样做,您可以隐藏依赖关系,而这正是您想使用依赖关系注入系统时要避免的东西.
By calling new
directly, you are not using PHP-DI. By doing this you are hiding the dependency, which is exactly what you are supposedly trying to avoid if you want to use a dependency injection system.
如果SystemUser
依赖(需要")SystemUserDetails
,则该依赖应该是显式的(例如,在其构造函数中声明).
If SystemUser
depends ("needs") SystemUserDetails
, the dependency should be explicit (e.g. declared in its constructor).
此外:对于这样的系统,您不需要定义文件.而且您在问题中显示的定义文件没有遵循 PHP-DI .
Furthermore: You do not need a definitions file for a system like this. And the definitions file you show in your question doesn't follow the best practices recommended by PHP-DI.
您的设计远非完美,我不确定您的最终目标,但是如果您这样做,它可能会起作用:
Your design is far from perfect, and I'm not sure of your end-goals, but if you did something like this, it could work:
<?php
// src/Database.php
class Database {
public function getDb() : string {
return 'veryDb';
}
}
<?php
// src/SystemUserDetails.php
class SystemUserDetails {
protected $db;
public function __construct(Database $db)
{
$this->db = $db;
}
public function getDetails() {
return "Got details using " . $this->db->getDb() . '.';
}
}
<?php
// src/SystemUser.php
class SystemUser {
protected $details;
public function __construct(SystemUserDetails $details, $userId=null) {
$this->details = $details;
}
public function getUser() {
return "Found User. " .$this->details->getDetails();
}
}
<?php
//init.php
require_once('vendor/autoload.php');
// build the container. notice I do not use a definition file.
$containerBuilder = new \DI\ContainerBuilder();
$container = $containerBuilder->build();
// get SystemUser instance from the container.
$userInstance = $container->get('SystemUser');
echo $userInstance->getUser(), "\n";
这将导致:
Found User. Got details using veryDb.
这篇关于如何获取PHP DI容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!