symfony2添加用于路由的动态参数,尝试使用自定义加载程序 [英] symfony2 add dynamic parameter for routing, try with custom loader

查看:86
本文介绍了symfony2添加用于路由的动态参数,尝试使用自定义加载程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在此处设置自定义路由器加载器

I try setup custom router loader like here

http://symfony.com/doc/current/cookbook/routing/custom_route_loader.html

我想添加动态参数对于所有路由(会话的参数)

i want add dynamic parameter for all routes (parameter from session)

这是我的代码

namespace Mea\Crm4Bundle\Routing;

use Mea\Crm4Bundle\Entity\Application;
use Symfony\Component\Config\FileLocatorInterface;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Loader\AnnotationClassLoader;
use Symfony\Component\Routing\Loader\AnnotationDirectoryLoader;
use Symfony\Component\Routing\Loader\AnnotationFileLoader;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Parser as YamlParser;
use Symfony\Component\Config\Resource\FileResource;

class AppLoader extends YamlFileLoader
{
    private static $availableKeys = array(
        'resource', 'type', 'prefix', 'pattern', 'path', 'host', 'schemes', 'methods', 'defaults', 'requirements', 'options', 'condition',
    );
    private $yamlParser;

    private $loaded = false;
    /**
     * @var
     */
    private $annotationClassLoader;
    /**
     * @var
     */
    private $session;

    /**
     * Constructor.
     *
     * @param FileLocatorInterface $locator A FileLocatorInterface instance
     * @param AnnotationClassLoader $annotationClassLoader
     * @param Session $session
     */
    public function __construct(FileLocatorInterface $locator, AnnotationClassLoader $annotationClassLoader, Session $session)
    {
        $this->locator = $locator;
        $this->annotationClassLoader = $annotationClassLoader;
        $this->session = $session;
    }


    public function load($file, $type = null)
    {

        $appId = $this->session->get(
            Application::CRM_APP_ID_SESSION
        );


        $path = $this->locator->locate($file);

        if (!stream_is_local($path)) {
            throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $path));
        }

        if (!file_exists($path)) {
            throw new \InvalidArgumentException(sprintf('File "%s" not found.', $path));
        }

        if (null === $this->yamlParser) {
            $this->yamlParser = new YamlParser();
        }

        try {
            $parsedConfig = $this->yamlParser->parse(file_get_contents($path));
        } catch (ParseException $e) {
            throw new \InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $path), 0, $e);
        }

        $collection = new RouteCollection();
        $collection->addResource(new FileResource($path));

        // empty file
        if (null === $parsedConfig) {
            return $collection;
        }

        // not an array
        if (!is_array($parsedConfig)) {
            throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $path));
        }

        foreach ($parsedConfig as $name => $config) {

            $config['defaults']['_applicationid']=$appId;

            if (isset($config['pattern'])) {
                if (isset($config['path'])) {
                    throw new \InvalidArgumentException(sprintf('The file "%s" cannot define both a "path" and a "pattern" attribute. Use only "path".', $path));
                }

                @trigger_error(sprintf('The "pattern" option in file "%s" is deprecated since version 2.2 and will be removed in 3.0. Use the "path" option in the route definition instead.', $path), E_USER_DEPRECATED);

                $config['path'] = $config['pattern'];
                unset($config['pattern']);
            }

            $this->validate($config, $name, $path);

            if (isset($config['resource'])) {
                $this->parseImport($collection, $config, $path, $file);
            } else {
                $this->parseRoute($collection, $name, $config, $path);
            }
        }

        return $collection;

    }

    public function supports($resource, $type = null)
    {
        return 'crmapp' === $type;
    }

}

这是routing.yml

here is routing.yml

mea_crm:
    resource: @MeaCrm4Bundle/Resources/config/routing.yml
    type: crmapp
    prefix: /{_applicationid}
    defaults:  { _applicationid: 5 }

这是服务.yml

  app.routing_loader:
            class: Mea\Crm4Bundle\Routing\AppLoader
            arguments: [@file_locator, @sensio_framework_extra.routing.loader.annot_class,@session]
            tags:
                - { name: routing.loader }

如果我删除缓存,此加载程序将被触发一次。
所以我认为这不是我所需要的。
我如何覆盖路由器或以其他方式-我希望从会话中设置_aplication id默认值。

This loader is fired once if i remove cache. So i think this is not what i need. How i can override router or in other way - i want setup _aplication id default value from session.

更新1

i设置路由器

这是工作方法

class RouteGenerator extends  UrlGenerator

public function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array()){


        if(!isset($parameters[MeaCrm4Bundle::CRM_APP_SWITCH_PARAMETER])){

            //for test
            $parameters[MeaCrm4Bundle::CRM_APP_SWITCH_PARAMETER] = 1212;

        }

        $url = parent::doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, $requiredSchemes);

        return $url;
    }

当我添加到parameter.yml

when i add to parameters.yml

router.options.generator_base_class: Mea\Crm4Bundle\Routing\RouteGenerator

我有我想要的-树枝,控制器使用此路由器并设置我的参数。只有一个-这不是服务,所以我没有@session
在这里获得会话的最佳方法是什么?

i have what i want - twig, controlerrs use this router and setup my parameter. Only one - this is not service so i dont have @session What is best method to get session here ?

您可以创建其他类-作为服务吗?我得到了覆盖树枝生成器的示例,但是有一种方法可以按服务而不是类覆盖主路由器?

Thy create other class - as service ? i get example to override twig generator but there exist way to override main router by service not class ?

UPDATE 2

所以我覆盖了路由器-但没有会话-我需要在这里

so i override router - but dont have session - i need like here

public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null, Session $session)
    {
        $this->routes = $routes;
        $this->context = $context;
        $this->logger = $logger;
        $this->session = $session;
    }

但是现在如何-如何在此处进行会话?

but what now - how get session here ?

推荐答案

我想您应该尝试实现 Symfony\Component\Routing\Generator\ UrlGeneratorInterface

或尝试扩展路由器并将其注册为服务。

Or try to extends the router and register it as a service.

然后您需要根据 TwigBundle 提供的扩展名来创建适当的扩展名:

Then you need to create the appropriate extension following the one provided by the TwigBundle:

<service id="twig.extension.routing" class="Symfony\Bridge\Twig\Extension\RoutingExtension" public="false">
    <argument type="service" id="router" />
</service>

将自定义生成器传递给它:

To pass it your custom generator:

<service id="app.twig.url_generator" class="AppBundle\Twig\Extension\RoutingExtension" public="false">
    <argument type="service" id="app.url_generator">
</service>

<service id="app.url_generator" class="AppBundle\Routing\AppUrlGenerator" public="false">
    <argument type="service" id="router">
    <argument type="service" id="session">
</service>

您需要装饰路由器以加载路由集合。

You need to decorate the router to load the route collection.

别忘了注册树枝扩展名:)

And don't forget to register the twig extension :)

这篇关于symfony2添加用于路由的动态参数,尝试使用自定义加载程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆