如何获取 PHP DI 容器?

How do I fetch the PHP DI container?

如何使用 PHP DI 加载数据库容器? 这是我迄今为止尝试过的变体之一。

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

<?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;
    }


    /**

Too few arguments to function MyApp\Models\SystemUser\SystemUserDetails::__construct(), 0 passed in /www/myapp/models/SystemUser.php on line 54 and exactly 1 expected File: /www/myapp/models/SystemUser/SystemUserDetails.php

数据库不应该自动加载吗?

跟踪:

  1. 目前,我的主要 index.php 文件扩展了 init.php,这是它创建容器的文件(在 post 中粘贴了代码部分)。

  2. 然后我调用 App class,它获取 URL(mysite.com/login/user_login) 并实例化一个新控制器 class 和 运行 提到的方法,在这种情况下,它是第一页 - MyApp/Contollers/Login.php.

    1. user_login 方法获取凭据,验证它们,如果它们有效,则使用 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 工作正常。

在你的 SystemUser class 你正在做的事情:

$this->systemUserDetatils   = new \MyApp\Models\SystemUser\SystemUserDetails();

SystemUserDetails 的构造函数需要一个 Database 对象,您没有传递它。

通过直接调用 new您没有使用 PHP-DI。通过这样做,您 隐藏了 依赖项,如果您想使用依赖项注入系统,这正是您应该试图避免的。

如果SystemUser depends ("needs") SystemUserDetails,依赖应该是显式的(例如在它的构造函数中声明)。

此外:对于这样的系统,您不需要定义文件。并且您在问题中显示的定义文件不遵循 the best practices recommended by PHP-DI.

您的设计远非完美,我不确定您的最终目标,但如果您这样做,它可能会奏效:

<?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.