Symfony 3 - 在实体__get()魔术方法中获取当前的“_locale”


Symfony 3 - Get current "_locale" inside an entity __get() magic method

谁能告诉我如何从实体类__get()魔法方法内部获取_locale

我已经检查了我想在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(),
    ));
}

不确定这是否适用于 S3,但在 Silex(S2 的"轻量级"版本)中,我刚刚采取了

$app = $GLOBALS['app']

然后通过以下方式访问区域设置

$app['locale'] .

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

上级:

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

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

按预期工作。