如何从苗条3中的单独类访问依赖容器?

时间:2016-07-08 17:41:16

标签: php dependency-injection php-7 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中不能有多个构造函数,并且我无法从类实例访问静态方法? 那么如何从无法存储在依赖项容器中的服务访问容器?

1 个答案:

答案 0 :(得分:0)

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

$ app-&gt; get(&#39; / find-user-by-username / {$ username}&#39;,function($ request,$ response,$ args){     $ result = \ User :: getByUsername($ args [&#39; username&#39;],$ this-&gt; 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
    }
}