Robert Brax
Robert Brax

Reputation: 7318

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

I have an isolated class file that is outside of a slim controller or cycle:

class UserModel
{


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

I want to replace the instantiation of the DbSql class by access to this service that is also registered in the slim container.

Question:

1) How do I access the slim container from this class?

2) I didn't see such example in the doc, is it something that should be avoided? Should I avoid accessing slim container from outside slim controller ?

Upvotes: 0

Views: 330

Answers (1)

jmattheis
jmattheis

Reputation: 11135

I didn't see such example in the doc

Thats probably because the container is a dependency from Slim -> Pimple

Should I avoid accessing slim container from outside slim controller ?

No, actually the container should be used for constructing all objects

How do I access the slim container from this class

You shouldn't access the DI-Container in the class. Rather the container should inject the needed instances in the constructor.

So first, when you havn't already done this add DbSql to the container:

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

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

Then add the UserModel to the container and add DbSql as constructor parameter

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

Add a constructor to the 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();
    }
}

Now you can get the UserModel from the container

$userModel = $container['UserModel'];

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

Upvotes: 1

Related Questions