1

我正在使用 Slim 3 构建一个休息 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 中有多个构造函数,而且我不能从类实例访问静态方法?那么如何从无法存储在依赖容器中的服务访问容器?

4

1 回答 1

0

您可以通过简单地将容器作为参数传递给 来访问容器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
    }
}
于 2016-10-03T12:07:35.003 回答