我正在构建一个Symfony 2.6网络应用程序和一个作曲家库。composer库对Symfony一无所知,需要使用其他框架(或者根本不使用框架)操作。
在某个时候,库需要重定向用户。当然,在一个简单的库中调用PHP的header('Location: x')
是很自然的。当使用直接的PHP和没有框架的库测试时,这是很好的。但是在Symfony应用程序中,调用库的控制器仍然需要创建一个Response
对象并返回它。实际上,创建一个空的Response
最终会清除重定向。我假设Symfony类创建了一个全新的标题集,覆盖了库中的Location
集。
那么,在不让我的库依赖Symfony的情况下,它如何能够重定向用户呢?
发布于 2015-02-06 07:07:50
使用库定义并通过依赖项注入使用的接口。
interface Redirector {
public function redirect($location, $code);
}
在库中,您可以将它作为参数传递给类构造函数,例如:
class FooBar {
private $redirector;
public function __construct(Redirector $red) {
$this->redirector = $red;
}
// ...
}
该接口的实现可以使用symfony的机制来执行实际的重定向,并且您的库不依赖于任何实现。
一项可能的执行可以是:
class SimpleRedirector implements Redirector {
public function redirect($location, $code) {
header('Location: ' . $location, true, $code);
die();
}
}
https://stackoverflow.com/questions/28368578
复制