我目前正在开发一个RESTful API来维护许多数据库。理想情况下,我应能够从我的应用程序中的其他路径调用我的API路由,对吗?
我尝试使用subRequest
来调用现有路由无效。
在Postman中执行我的路线时,我得到的是以下内容:
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<title>Slim Application Error</title>
<style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}</style>
</head>
<body>
<h1>Slim Application Error</h1>
<p>A website error has occurred. Sorry for the temporary inconvenience.</p>
</body>
</html>
以下是我的companies.php
API路由,用于获取表格中的所有公司并将新公司放入companies
表格。
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
// Get all companies
$app->get('/companies', function(Request $request, Response $response) {
$sql = "SELECT * FROM companies";
try {
// Get DB Object
$db = new db();
// Connect
$db = $db->connect();
$stmt = $db->query($sql);
$companies = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"data":' . json_encode($companies) . '}';
} catch(PDOException $e) {
echo '{"error": { "text":' . $e->getMessage() . '}}';
}
});
// Add new company to companies table
$app->put('/new/company/{companyName}', function(Request $request, Response $response) {
$newCompany = $request->getAttribute('companyName');
$insert_sql = "INSERT INTO companies (company_name) VALUE (:newCompany)";
try {
$db = new db();
$db = $db->connect();
$insert_stmt = $db->prepare($insert_sql);
$newCompany = str_replace("'", "", $newCompany);
$insert_stmt->bindParam(':newCompany', $newCompany);
$insert_stmt->execute();
$newID = $db->lastInsertId();
$db = null;
echo '{"notice": {"text": "New Company Added (cid: '.$newID.')"}';
} catch(PDOException $e) {
echo '{"error": { "text":' . $e->getMessage() . '}}';
}
});
在不同的路线sites.php
内,我想运行PUT->'/new/company'
路线。所以,在sites.php
范围内的某处我放置以下内容:
$destinationComp = "myNewCompany";
$res = $this->subRequest('PUT', '/new/company/' . $destinationComp);
echo $res;
我希望我的输出与从Postman手动发出PUT请求相同,而不是第一个代码段中列出的错误。
此外,我已尝试修改我的路线调用以包含use ($app)
,希望通过$app
变量而不是$this
定期发出请求,情况为$this
没有用。看起来像是:
$app->put('/new/site/{sourceCompany}/{sourceProperty}/{destinationCompany}/{destinationProperty}', function(Request $request, Response $response) use ($app) {
$destinationComp = "myNewCompany";
$res = $app->put("/new/company/$destinationComp");
echo $res;
//More code to follow...
}
仅在执行时在Postman中收到相同的错误消息。
有什么建议吗?
答案 0 :(得分:1)
您试图在Container类上调用subRequest方法,它应该是App类。
在路由闭包内,$ this绑定到Slim \ Container的实例 - Slim docs
引用$ app var,用use关键字注入它。另外,返回响应对象而不是回显:
.xcworkspace