php - Symfony - 从命令文件中检索当前用户
问题描述
我目前正在研究一个非常古老的 Symfony 2.4 项目。
我创建了一个 CsvImportCommand 文件来创建具有 csv 功能的大量客户。
我需要将当前登录用户设置为我的列“created_by”的值,但我不知道如何获取此信息。
我看到我可以在树枝模板中使用app.user
或get('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();
}
}
解决方案
关于你的错误:
您不能在类变量中使用 $this 。你必须在 __construct 中分配 $user 或者你创建 set-Methods。像:setUser。
关于带有命令的安全捆绑:
你不能使用 security.context 因为你在这个部分没有用户。也许你可以伪造它,但这不是很好。
推荐阅读
- android - 遵守 Play 商店的后台位置规则有哪些要求?
- gcc - 在 Big Sur 中编译 Rcpp 包时出现 Clang 错误
- android - 在 Android 11 上访问外部存储(目标 sdk 版本为 29)
- r - 为什么我的“如果”论点不能解释为合乎逻辑的
- ios - UIImagePicker 不返回图像
- sql - SQL - YearMonth 整数的滞后/延迟
- python - 使用 Python 和 Pandas 将员工数据库与代理电子邮件合并
- tendermint - 如何在 Tendermint websocket /subscribe 方法中使用 OR 条件?
- javascript - 单击时反应路由器链接不更新端点
- azure - 如何通过 C# 创建 Azure API 管理实例?