我看到了一件非常有趣的事情。我在Slim框架的基础上做了一个小的mvc/rest框架。
$app->put('/:id', function ($id) {
$app->halt(500, "Error") // Here this is working.
(new RestController)->editItem($id);
})->via('put');
所以我写了一个RestController,它扩展了BaseController,我的BaseController扩展了Slim框架。
class BaseController extends SlimSlim {
/**
* @var appmodelsAbstractModel
*/
protected $model;
public function __construct() {
$settings = require(__DIR__ .'/../configurations/slim.php');
parent::__construct($settings);
}
}
所以我的BaseController可以使用Slim类的方法和属性。
class RestController extends BaseController {
public function editItem($id) {
$data = $this->getRequestBody();
$result = $this->model->update($id, $data['data']);
// This is absolutely not working, but it seems my application will die in this case.
// Because I cannot see any written message (with echo or print methods...)
// This will always return with a 200 staus code and blank page!
$this->halt(404, json_encode(array('status' => "ERROR")));
}
}
但这会很好。。。我不明白,为什么?
class RestController extends BaseController {
public function editItem($id) {
$data = $this->getRequestBody();
$result = $this->model->update($id, $data['data']);
// This will work.
$app = Slim::getInstance();
$app->halt(204, json_encode(array('status' => "ERROR")));
}
}
有人有好的ide吗?
您通过执行(new RestController)
在路由中构造一个新的RestController。尽管它在类层次结构中扩展了Slim/Slim,但它是它的一个新实例;它不是实际运行的Slim应用程序$app
的副本或引用。
这在第一种情况下会导致问题:您说$this->halt(...)
,而$this
是新建的RestController,它是Slim应用程序的新实例,而不是当前正在运行的实例。因此,暂停调用对应用程序的输出没有影响。
在第二种情况下,您说$app->halt(...)
,其中$app是Slim::getInstance()
,即Slim应用程序的全局实例,它是实际运行的Slim应用。因此,暂停调用会对应用程序的输出产生影响。
您可以使用第二种方法来解决问题,也可以将全局$app
变量实例化为RestController,然后您可以执行以下操作:
$app->put('/:id', function ($id) use ($app) {
$app->halt(500, "Error") // Here this is working.
$app->editItem($id);
})->via('put');
NB;你忘了把use ($app)
放在你的问题发布的代码中,我在上面的代码中添加了它。它是否存在于您实际运行的代码中?否则,$app->halt()
调用无论如何都会导致错误。