2016-03-26 26 views
1

Burada gibi kurulum özel yönlendirici yükleyici deneyin özel yükleyici ile deneyin, yönlendirme için dinamik parametre eklemekSymfony2'nin

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

ben bu tüm yolları (oturumdan parametresi)

için dinamik parametre eklemek istediğiniz

benim kod

burada
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 olan

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

i önbelleği kaldırırsanız, bu yükleyici kez etkinleştirilir services.yml

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

olduğunu. Yani bence ihtiyacım olan şey bu değil. Yönlendiriciyi nasıl geçersiz kılabilirim veya başka bir şekilde nasıl yapabilirim - setup _aplication id varsayılan değeri oturumdan istiyorum.

GÜNCELLEME 1

i kurulum yönlendirici

burada

çalışıyor yöntem

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; 
    } 

i

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

parameters.yml eklemek i istediğimi elde - dal, controlerrs bu yönlendiriciyi kullanır ve parametemi ayarlar. Sadece bir - bu hizmet değil ben Session var Burada oturum almak için en iyi yöntem nedir?

Thy diğer sınıfı oluştur - hizmet olarak mı? Ben twig jeneratörü geçersiz kılmak için örnek var ama hizmet değil sınıf tarafından ana yönlendirici geçersiz kılma yolu var? sahip oturumu ama dont - -

GÜNCELLEME

2 yüzden yönlendirici geçersiz ben şimdi burada

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

ama ne gibi ihtiyaç - Buradan nasıl oturumu olsun?

+0

kayıt unutma? – Heah

+0

Örnek olarak buna ihtiyacım var - şablonda rota oluşturuyorum - {{yol ('MeaTask_View', {id: task.id})}} - bu nedenle bu listeden otomatik olarak ekleme eklemelisiniz _applicationId. yol MeaTask_View @ MeaCrm4Bundle/Resources/config/routing.yml yani bu parametreyi kullanın, ancak her zaman varsayılanları kullanın: {_applicationid: 5} –

+0

Evet, dinleyicide ayarlayabilirim - biraz test yapıyorum - buradaki gibi, istekte bulunmak için http : //stackoverflow.com/questions/36223693/symfony2-how-to-add-a-global-parameter-to-routing-for-every-request-or-generat ancak varsayılan yönlendirici olarak simetrik kullanımı nasıl kullanacağınızı bilmiyorum –

cevap

1

Symfony\Component\Routing\Generator\UrlGeneratorInterface'u uygulamayı denemelisiniz. Veya yönlendiriciyi genişletmeyi ve hizmet olarak kaydetmeyi deneyin. Sen yüklemek için yönlendirici süslemek için ihtiyaç

<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> 

:

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

o özel jeneratör geçmek için:

Sonra TwigBundle tarafından sağlanan aşağıdaki uygun uzantı oluşturmak gerekir rota koleksiyonu

Ve dal uzantısı :) Eğer bu değer geri almak gerekiyor

+0

Tamam ama sadece twig değil tüm rotalar için bu değişiklik gerekiyor. buldum - varsayılan yönlendirici parametresini kullanın - router.options.generator_base_class: Mea \ Crm4Bundle \ Yönlendirme \ RouteGenerator - sınıfımı zorladım ve çalışıyorum :) ama hizmete ihtiyacım var - oturum servisine ihtiyacım var. İtme hizmeti sınıf değil midir? Sory - bu bilgiyi app.url_generator verirsiniz - şimdi deneyin. –

+0

Router'ınızı jeneratörü argümanı olarak geçirmeniz ve daha sonra jeneratörü yönlendiriciye geri itmesi gariptir. Yönlendiriciyi genişletmeli ve bunun yerine ebeveyn çağırırken gerekli yöntemleri geçersiz kılmalısınız. – Heah

+0

İyi anladığımdan emin değilim - bu yüzden hizmetleri kullanmayın, ancak yönlendiricimi parametrelerime göre ayarlayın. –