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?
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
}
}