symfony 3.3 自定义路由器

symfony 3.3 custom router

我有一个应用程序,它可以通过登录和具有相同路由的 OAuth 客户端密钥双重访问。对于 Oauth 访问,我需要传递一个 url 参数:"access_token" 在所有 url 上。

似乎最好使用自定义路由器来实现此目的:

app/config/services.yml

# Learn more about services, parameters and containers at
# https://symfony.com/doc/current/service_container.html
parameters:
    router.class: AppBundle\Routing\AccessTokenRouter

services:
    # default configuration for services in *this* file
    _defaults:
        # automatically injects dependencies in your services
        autowire: true
        # automatically registers your services as commands, event subscribers, etc.
        autoconfigure: true
        # this means you cannot fetch services directly from the container via $container->get()
        # if you need to do this, you can override this setting on individual services
        public: false

    # makes classes in src/AppBundle available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    AppBundle\:
        resource: '../../src/AppBundle/*'
        # you can exclude directories or files
        # but if a service is unused, it's removed anyway
        exclude: '../../src/AppBundle/{Entity,Tests}'

    # controllers are imported separately to make sure they're public
    # and have a tag that allows actions to type-hint services
    AppBundle\Controller\:
        resource: '../../src/AppBundle/Controller'
        public: true
        tags: ['controller.service_arguments']

    # add more services, or override services that need manual wiring
    # AppBundle\Service\ExampleService:
    #     arguments:
    #         $someArgument: 'some_value'
    app.access_token_user_provider:
        class: AppBundle\Security\AccessTokenuserProvider
        arguments: ["@doctrine.orm.entity_manager"]

AppBundle\Routing\AccessTokenRouter

use Symfony\Bundle\FrameworkBundle\Routing\Router as BaseRouter;

class AccessTokenRouter extends BaseRouter
{
    public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
    {
        // parent router generates url
        $url = parent::generate($name, $parameters, $referenceType);

        // check for existing preview query string
        parse_str($this->getContext()->getQueryString(), $contextQueryParams);
        if(isset($contextQueryParams['access_token']))
        {
            // put possible query string params into $queryParams array
            $urlParts = parse_url($url);
            parse_str(isset($urlParts['query']) ? $urlParts['query'] : '', $urlQueryParams);

            // strip everything after '?' from generated url
            $url = preg_replace('/\?.*$/', '', $url);

            // append merged query string to generated url
            $url .= '?'.http_build_query(array_merge(
                                             array('access_token' => $contextQueryParams['access_token']),
                                             $urlQueryParams
                                         ));
        }

        return $url;
    }
}

我没有收到任何错误,但从未调用过自定义路由器。

另外,当我调试路由时:

bin/console debug:container |grep rout

 data_collector.router             Symfony\Bundle\FrameworkBundle\DataCollector\RouterDataCollector                            
 monolog.logger.router             Symfony\Bridge\Monolog\Logger                                                               
 router                            alias for "router.default"                 
 router_listener                   Symfony\Component\HttpKernel\EventListener\RouterListener                                   
 routing.loader                    Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader                                     
 web_profiler.controller.router    Symfony\Bundle\WebProfilerBundle\Controller\RouterController  

我对这条线感到困惑

    alias for "router.default" 

我找不到这方面的任何文档。

Symfony 中似乎发生了一些变化,但我找不到什么

您确定参数 router.class 吗?我没找到so参数...

尝试制作自定义 url 生成器

配置

parameters:
    router.options.generator_class: AppBundle\Routing\AccessTokenUrlGenerator
    router.options.generator_base_class: AppBundle\Routing\AccessTokenUrlGenerator

和class

use Symfony\Component\Routing\Generator\UrlGenerator as BaseUrlGenerator ;

    public function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, $requiredSchemes)
    {
        // parent router generates url
        $url = parent::doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, $requiredSchemes);

        // check for existing preview query string
        parse_str($this->getContext()->getQueryString(), $contextQueryParams);
        if(isset($contextQueryParams['access_token']))
        {
            // put possible query string params into $queryParams array
            $urlParts = parse_url($url);
            parse_str(isset($urlParts['query']) ? $urlParts['query'] : '', $urlQueryParams);

            // strip everything after '?' from generated url
            $url = preg_replace('/\?.*$/', '', $url);

            // append merged query string to generated url
            $url .= '?'.http_build_query(array_merge(
                                             array('access_token' => $contextQueryParams['access_token']),
                                             $urlQueryParams
                                         ));
        }

        return $url;
    }
}

router.class 我认为在较旧的 symfoy 版本中使用 router.options.generator_class 而不是