嗨,我已经从自编的惯性发动机切换到了ph ple的路线。我的问题是:我可以在路由操作方法之外访问通配符变量吗?
路由部分:
$router = new League\Route\RouteCollection;
$router->addRoute('GET', '{locale}/{controller}/{action}', '\Backend\Controller\{controller}Controller::{action}');
$dispatcher = $router->getDispatcher();
//making a call with, for example, '/en/foo/bar', or '/de/foo/bar'
$response = $dispatcher->dispatch($oRequest->getMethod(), $oRequest->getPathInfo());
$response->send();
控制器部分
class FooController extends AppController {
public function __construct() {
//<---- here i want to access the {locale} from the URI somehow
}
public function bar(Request $request, Response $response, array $args) {
// $args = [
// 'locale' => 'de', // the actual value of {locale}
// 'controller' => 'foo' // the actual value of {controller}
// 'action' => 'bar' // the actual value of {bar}
// ];
}
}
中找不到任何内容
我正在使用&#34;联盟/路线&#34;:&#34; ^ 1.2&#34;
答案 0 :(得分:1)
我认为默认情况下,你只能静态地调用控制器类中的方法,当你这样做时,控制器的构造函数不会被自动调用。而且你也不能使用路由的通配符来动态调用控制器。
请注意,这不安全,但您仍然可以使用Custom Strategy在联盟/路线中执行您想要的操作:
控制器
class TestController {
public function __construct($args) {
//the wildcards will be passed as an array in the constructor like this
$this->locale = $args['locale'];
}
public function check(Request $request, Response $response, array $args) {
// $args = [
// 'locale' => 'de', // the actual value of {locale}
// 'controller' => 'Test' // the actual value of {controller}
// 'action' => 'check' // the actual value of {action}
// ];
return $response;
}
}
自定义策略
class CustomStrategy implements StrategyInterface {
public function dispatch($controller, array $vars)
{
$controller_parts = [];
foreach($controller as $con){
foreach ($vars as $key => $value) {
$placeholder = sprintf('{%s}', $key);
$con = str_replace($placeholder, $value, $con);
}
$controller_parts[] = $con;
}
//the controller will be instantiated inside the strategy
$controllerObject = new $controller_parts[0]($vars);
//and the action will be called here
return $controllerObject->$controller_parts[1](Request::createFromGlobals(),new Response(),$vars);
}
}
使用自定义策略集成进行路由
$router = new League\Route\RouteCollection;
$router->setStrategy(new CustomStrategy()); //integrate the custom strategy
$router->addRoute('GET', '/{locale}/{controller}/{action}', '{controller}Controller::{action}');
$dispatcher = $router->getDispatcher();
//if your url is /en/Test/check, then TestController->check() will be called
$response = $dispatcher->dispatch($oRequest->getMethod(), $oRequest->getPathInfo());
$response->send();