how to use a dependency container in a php file that isn't a class in Slim 3

60 views Asked by At

I have this dependency container for my database.

$container['db'] = function ($container) {
    $db = $container['settings']['db'];
    $conn = db2_connect($db['database'], $db['username'], $db['password']);
    return $conn;
};

I can use this in my controller like this $conn = $this->db; to query my database and return an array.

I am trying to do an ajax call to use datatables in a view. When I create a page for my ajax call it's just a php file. Not a class. How do I use the db container in this php file?

here is the php file.

if ($conn) {
    $sql = "SELECT trannum, 
                   trantype, 
                   tranbatch, 
                   trandate, 
                   username, 
                   trvnum, 
                   tranaccount, 
                   tranamt, 
                   transtatus, 
                   trannumdocs 
            FROM   BD.BDPTV 
                   INNER JOIN BD.BDUSERS 
                           ON BD.BDUSERS.usernumber = BD.BDPTV.tranuser 
            WHERE  transtatus NOT IN ( 3, 7, 5 )";

    $stmt = db2_prepare($conn, $sql);

    if ($stmt) {
        $result = db2_execute($stmt);
        if ($result) {
            while ($row = db2_fetch_array($stmt)) {
                $admin[] = array(
                    'trnum' => $row[0],
                    'trtyp' => $row[1],
                    'trbatch' => $row[2],
                    'trdate' => $row[3],
                    'usrnam' => $row[4],
                    'trvnum' => $row[5],
                    'tracct' => $row[6],
                    'tramt' => $row[7],
                    'trvsts' => $row[8],
                    'numdoc' => $row[9]
                );
            }
        } else {
            error_log(db2_stmt_errormsg($stmt));
        }
    } else {
        error_log(db2_stmt_errormsg($stmt));
    }
} else {
    error_log(db2_conn_errormsg());
}

multiDim($admin);
$admin['data'] = $admin;
echo json_encode($admin);
1

There are 1 answers

10
jmattheis On

You can access the db-object in 2 ways first the 'array' style (like you've defined it)

$conn = $container['db'];

or via the get-method

$conn = $container->get('db');

Nevertheless you should add a route in Slim to do that, not add an extra PHP file for that. This is not the usecase for Slim.