douduan2272 2016-07-08 17:41
浏览 22

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

I am using Slim 3 to build a rest API, and i have this structure

# 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

    }

}

?>

i cant store the user model in the dependency container because, i can't have multiple constructors in PHP, and i can't access static methods from class instance? so how do i access the container from a service that can't be stored in the dependency container?

  • 写回答

1条回答 默认 最新

  • duanlie2709 2016-10-03 12:07
    关注

    You can access the container by simply passing it as an argument to User::getByUsername, like this:

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

    However, consider changing the architecture of your application. Container is the thing from which you take stuff, you don't inject it, because such injection removes the very purpose of the container.

    Assuming that you want to grab user instance from storage, like database, you could do it like this:

    // 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
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题