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

时间:2016-04-27 09:23:59

标签: php symfony

有人能告诉我如何从实体类内的_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(),
    ));
}

1 个答案:

答案 0 :(得分:2)

不确定这是否适用于S3,但是在Silex(&#39; light&#39;版本的S2)中我只是采用了

$app = $GLOBALS['app']

然后通过

访问区域设置

$app['locale']

所以我猜你的解决方案几乎是一样的,也许只有另一种语法。

UPD:

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

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

按预期工作。