从 class 不在超薄控制器中访问容器的正确方法
Proper way to access the container from a class not in a slim controller
我在控制器之外有一个常规的 php class,因此它无法从容器的自动注入中获益。我需要从那个 class 访问响应对象,我想我应该从容器中获取它。
访问它的正确方法是什么?只需将它作为参数传递,以便外部 class 可以使用它吗?有没有更好的方法?
你需要为此使用中间件,因为响应对象是不可变的,所以 "changing" 它不会更新 slim 将使用的响应。
$app->add(function($request, $response, $next) {
if($shouldRedirect === true) {
return $response->withRedirect('myurl'); // do not execute next middleware/route and redirect
}
return $next($request, $response); // execute next middleware/ the route
});
有关中间件的更多信息have a look at this。
如果你需要发送一个子请求,Slim provides such functionality. Use it carefully 不过,在某些情况下它的结果并不明显。
<?php
class MySortOfOutsideClass
{
/**
* If you need to send a subrequest, you have to access application instance,
* so let's inject it here.
*/
public function __construct(\Slim\App $app)
{
$this->$app = $app;
}
/**
* Method that makes a subrequest, and returns the result of it.
*/
public function myMethod()
{
if ($subRequestIsRequired) {
return $this->app->subRequest('GET', '/hello');
}
}
}
我在控制器之外有一个常规的 php class,因此它无法从容器的自动注入中获益。我需要从那个 class 访问响应对象,我想我应该从容器中获取它。 访问它的正确方法是什么?只需将它作为参数传递,以便外部 class 可以使用它吗?有没有更好的方法?
你需要为此使用中间件,因为响应对象是不可变的,所以 "changing" 它不会更新 slim 将使用的响应。
$app->add(function($request, $response, $next) {
if($shouldRedirect === true) {
return $response->withRedirect('myurl'); // do not execute next middleware/route and redirect
}
return $next($request, $response); // execute next middleware/ the route
});
有关中间件的更多信息have a look at this。
如果你需要发送一个子请求,Slim provides such functionality. Use it carefully 不过,在某些情况下它的结果并不明显。
<?php
class MySortOfOutsideClass
{
/**
* If you need to send a subrequest, you have to access application instance,
* so let's inject it here.
*/
public function __construct(\Slim\App $app)
{
$this->$app = $app;
}
/**
* Method that makes a subrequest, and returns the result of it.
*/
public function myMethod()
{
if ($subRequestIsRequired) {
return $this->app->subRequest('GET', '/hello');
}
}
}