如何在 slim 3 中从单独的类访问依赖项容器


how to access dependency container from separate class in slim 3?

我正在使用 Slim 3 来构建一个 rest API,我有这个结构

# models/user.php
<?php
class User {
    public $id;
    public $username;
    public $password;
    public $number;
    public $avatar;
    function __construct($id, $username, $password, $number, $avatar = null, $active = false) {
      $this -> id = $id;
      $this -> username = $username;
      $this -> password = $password;
      $this -> number = $number;
      $this -> avatar = $avatar;
      $this -> active = $active;
    }
    static function getByUsername($username) {
        // i want to access the container right here
    }
}
?>

我无法将用户模型存储在依赖项容器中,因为 PHP 中不能有多个构造函数,并且无法从类实例访问静态方法?那么,如何从无法存储在依赖项容器中的服务访问容器呢?

您可以通过简单地将其作为参数传递给 User::getByUsername 来访问容器,如下所示:

$app->get('/find-user-by-username/{$username}', function($request, $response, $args) { $result = ''User::getByUsername($args['username'], $this->getContainer());});

但是,请考虑更改应用程序的体系结构。容器是你从中取出东西的东西,你不会注入它,因为这种注入消除了容器的目的。

假设你想从存储中获取用户实例,比如数据库,你可以这样做:

// application level
$app->get('/find-user-by-username/{$username}', function($request, $response, $args) {
    // assuming you're using PDO to interact with DB,
    // you get it from the container 
    $pdoInstance = $this->container()->get('pdo');
    // and inject in the method
    $result = 'User::getByUsername($args['username'], $pdoInstance);
});
// business logic level
class User
{
    public static function getByUsername($username, $dbInstance)
    {
        $statement = $dbInstance->query('...');
        // fetching result of the statement
    }
}