在非控制器上使用 slim 容器的正确方法是什么(如果有的话)class

what is the right way (if any) to use the slim container on a non controller class

我有一个独立的 class 文件,它位于 slim 控制器或循环之外:

class UserModel
{


    public function getSingleUser( string $field, $value )
    {
        return ( new DbSql )->db()->table( 'users' )->where( $field, $value )->first();
    }
}

我想通过访问也在 slim 容器中注册的此服务来替换 DbSql class 的实例化。

问题:

1) 如何从此 class 访问 slim 容器?

2) 我在文档中没有看到这样的例子,这是应该避免的事情吗?我应该避免从外部 slim 控制器访问 slim 容器吗?

I didn't see such example in the doc

这可能是因为容器是 Slim 的依赖 -> Pimple

Should I avoid accessing slim container from outside slim controller ?

不,实际上应该使用容器来构造所有对象

How do I access the slim container from this class

您不应该访问 class 中的 DI 容器。相反,容器应该在构造函数中注入所需的实例。

所以首先,如果您还没有这样做,请将 DbSql 添加到容器中:

$app = \Slim\App();
$container = $app->getContainer();

$container['DbSql'] = function($c) {
    return new DbSql();
};

然后将UserModel添加到容器中并添加DbSql作为构造函数参数

$container['UserModel'] = function($c) {
    return new UserModel($c['DbSql']);
};

UserModel

添加构造函数
class UserModel {
    private $dbSql;

    public function __construct(DbSql $dbSql) {
        $this->dbSql = $dbSql;
    }

    public function getSingleUser( string $field, $value ) {
        return $this->dbSql->db()->table( 'users' )->where( $field, $value )->first();
    }
}

现在可以从容器

中获取UserModel
$userModel = $container['UserModel'];

$user = $userModel->getSingleUser('name', 'jmattheis');