首页 > 解决方案 > Symfony - 从命令文件中检索当前用户

问题描述

我目前正在研究一个非常古老的 Symfony 2.4 项目。

我创建了一个 CsvImportCommand 文件来创建具有 csv 功能的大量客户。

我需要将当前登录用户设置为我的列“created_by”的值,但我不知道如何获取此信息。

我看到我可以在树枝模板中使用app.userget('security.context')->getToken()->getUser()在控制器文件中获取此信息。

但我真的不知道如何在命令文件中检索这些信息。

请记住,这是一个 Symfony 2.4 项目。

下面是我的代码,它返回一个错误: PHP Parse error: syntax error, unexpected '$this' (T_VARIABLE) (on my 2nd line)

class CsvImportCommand extends ContainerAwareCommand
{

    private $user = $this->get('security.context')->getToken()->getUser();
    private $username = $user->getUsername();

    protected function configure()
    {
        $this
            ->setName('csv:import')
            ->setDescription('Import users from CSV file')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $now = new \DateTime();
        $output->writeln('<comment>Start:' . $now->format('d-m-Y G:i:s') . '---</comment>');

        $this->import($input, $output);

        $now = new \DateTime();
        $output->writeln('<comment>End:' . $now->format('d-m-Y G:i:s') . '---</comment>');
    }

    protected function import(InputInterface $input, Outputinterface $output)
    {
        $data = $this->get($input, $output);

        $em = $this->getContainer()->get('doctrine')->getManager();

        $em->getConnection()->getConfiguration()->setSQLLogger(null);

        $size = count($data);
        $batchSize = 20;
        $i = 1;

        foreach($data as $row) {
            $person = $em->getRepository('MyBundle:Person')->findOneBy(array('firstname'=>$row['firstname'], 'lastname'=>$row['lastname']));

            if(!$person){
                $person = new Person();
                $em->persist($person);
            }
            $person->setIsPrivate($row['is_private']);
            $person->setCivility($row['civility']);
            $person->setFirstName($row['firstname']);
            $person->setLastName($row['lastname']);
            $person->setPhoneHome($row['phone_home']);
            $person->setMobileHome($row['mobile_home']);
            $person->setEmailPro($row['email_pro']);
            $person->setEmailHome($row['email_home']);
            $person->setCreatedAt(new \DateTime());
            $person->setUpdatedAt(new \DateTime());
            $person->setCreatedBy($username);

            if (($i % $batchSize) === 0) {
                $em->flush();
                $em->clear();

                $now = new \DateTime();
                $output->writeln('of users imported... | ' . $now->format('d-m-Y G:i:s'));
            }

            $i++;
        }

        $em->flush();
        $em->clear();
    }
}

标签: phpsymfony

解决方案


关于你的错误:

您不能在类变量中使用 $this 。你必须在 __construct 中分配 $user 或者你创建 set-Methods。像:setUser。

关于带有命令的安全捆绑:

你不能使用 security.context 因为你在这个部分没有用户。也许你可以伪造它,但这不是很好。


推荐阅读