[英]how to use a dependency container in a php file that isn't a class in Slim 3
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;
我可以在控制器中像
$conn = $this->db;
这样使用它$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. 我试图做一个ajax调用在视图中使用数据表。 When I create a page for my ajax call it's just a php file.
当我为ajax调用创建页面时,它只是一个php文件。 Not a class.
不上课。 How do I use the db container in this php file?
如何在此php文件中使用db容器?
here is the php file. 这是PHP文件。
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);
You can access the db
-object in 2 ways first the 'array' style (like you've defined it) 您可以通过两种方式首先使用“数组”样式访问
db
-object(就像您已定义它一样)
$conn = $container['db'];
or via the get
-method 或通过
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. 不过,您应该在Slim中添加一条路由来做到这一点,而不是为此添加额外的PHP文件。 This is not the usecase for Slim.
这不是Slim的用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.