如何获取 PHP DI 容器?

W. 是的

如何使用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();

系统用户详细信息.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() 的参数太少,0 在第 54 行传入 /www/myapp/models/SystemUser.php 和 1 预期文件:/www/myapp/models/SystemUser/SystemUserDetails .php

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

痕迹:

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

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

    1. 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);
            }
        }
    }
}
伊薇

PHP-DI 工作正常。

在你的SystemUser课堂上,你正在做:

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

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

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

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

此外:对于这样的系统,不需要定义文件并且您在问题中显示的定义文件不遵循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.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章