hpleague路由-uri中的locale


thephpleague route - locale in uri

嗨,我从一个自己编写的路由引擎切换到了hpleague路由。我的问题是:我可以访问路由操作方法之外的通配符变量吗?

示例


路由部分:

$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}
        // ];
    }
}

我在文件中找不到任何东西

我使用的是"联赛/路线":"^1.2"

我认为默认情况下,您只能静态调用控制器类中的方法,并且当您这样做时,不会自动调用控制器的构造函数。此外,您也不能使用路由的通配符来动态调用控制器。

请注意,这是不安全的,但您仍然可以使用联盟/路线中的自定义策略执行您想要的操作,如下所示:


控制器

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();