2016-04-27 89 views
0

任何人都可以告诉我如何从__get()里面获得_locale魔法方法吗?Symfony 3 - 在实体内部获取当前的“_locale”__get()魔法

我检查中,我想获得这种类型的数据在getLocale()方法适当的位置:

<?php 

namespace Notimeo\PageBundle\Entity; 

use Doctrine\Common\Collections\ArrayCollection; 
use Doctrine\ORM\Mapping as ORM; 
use Notimeo\CoreBundle\Ext\Entity\Locales; 
use Notimeo\PageBundle\Entity\Page\PageFile; 
use Vich\UploaderBundle\Mapping\Annotation as Vich; 
use Symfony\Component\Validator\Constraints as Assert; 
use Notimeo\UserBundle\Entity\User; 

/** 
* Page 
* 
* @ORM\Table(name="pages") 
* @ORM\Entity(repositoryClass="Notimeo\PageBundle\Repository\PageRepository") 
* @ORM\HasLifecycleCallbacks 
*/ 
class Page extends Locales 
{ 
    // ... 

    /** 
    * @Assert\Valid 
    * @ORM\OneToMany(
    *  targetEntity="Notimeo\PageBundle\Entity\Page\PageLocale", 
    *  mappedBy="page", 
    *  cascade={"persist","remove"}, 
    *  orphanRemoval=true 
    *) 
    * @var Page\PageLocale[] 
    */ 
    protected $locales; 

    // ... 

    function __get($name) 
    { 
     $className  = get_class($this); 
     $exploded  = explode('\\', $className); 
     $localeClassName = $className.'\\'.array_pop($exploded).'Locale'; 

     if(property_exists($localeClassName, $name)) { 
      return $this->getLocale()->$name; 
     } 

     return null; 
    } 

    public function getLocale($lang = '') 
    { 
     if('' === $lang) { 
      $lang = GET_CURRENT_LANG_HERE; // <- !!!!!!! 
     } 

     foreach($this->locales as $locale) { 
      if($locale->getLang() === $lang) { 
       return $locale; 
      } 
     } 

     throw new \Exception('No locale found in this language.'); 
    } 

    // ... 
} 

我的控制器动作,在那里我加载实体:

protected function listAction() 
{ 
    $this->dispatch(EasyAdminEvents::PRE_LIST); 

    $fields = $this->entity['list']['fields']; 
    $paginator = $this->findAll(
     $this->entity['class'], 
     $this->request->query->get('page', 1), 
     $this->config['list']['max_results'], 
     $this->request->query->get('sortField'), 
     $this->request->query->get('sortDirection') 
    ); 

    $this->dispatch(
     EasyAdminEvents::POST_LIST, 
     array('paginator' => $paginator) 
    ); 

    $deleteForm = $this->createDeleteForm($this->entity['name'], '__id__'); 

    return $this->render($this->entity['templates']['list'], array(
     'paginator'   => $paginator, 
     'fields'    => $fields, 
     'delete_form_template' => $deleteForm->createView(), 
    )); 
} 

回答

2

不知道如果这在S3中工作,但在Silex(S2的“轻”版本)中,我只需要

$app = $GLOBALS['app']

然后通过访问区域设置

$app['locale']

所以我想你的解决方案将几乎相同,也许只有另一种语法。

UPD:

刚刚在S3中处理了这种情况。

$current_locale = $GLOBALS['app']['locale']; 

按原样工作。

+0

所以请标记为答案 – GodlyHedgehog

相关问题