繁体   English   中英

在 Symfony 命令中使用自定义服务

[英]Use custom service in a Symfony Command

我创建了一个带有我想从命令窗口运行的 PHP 函数的类。

因此,我创建了一个类扩展命令,但我遇到了麻烦,因为我必须调用EntityManagerInterfaceUserPasswordHasherInterface

如果我将它们放在构造函数中并创建一个新实例,我会被要求提供两个参数,我猜不出来。 那么当我调用我的方法时使用这两个接口的解决方案是什么?

这是我的 2 个文件:TestHashPassword

<?php

namespace App;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class TestHashPassword
{
    private $entityManager;
    private $passwordHasher;

    public function __construct(EntityManagerInterface $em,UserPasswordHasherInterface $passwordHasherInterface){
        $this->entityManager = $em;
        $this->passwordHasher = $passwordHasherInterface;

        parent::__construct();
    }

    public function hashPassword(){
        $em = $this->entityManager; // will throw an error  "Using $this when not in object context"
        $userAll = $em
            ->getRepository(User::class)
            ->findAll();
        echo("coucou");


        foreach($userAll as $user){
            $comb = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
            $pass = array();
            $combLen = strlen($comb) - 1;
            for ($i = 0; $i < 8; $i++) {
                $n = rand(0, $combLen);
                $pass[] = $comb[$n];
            };
            echo("coucou");
            $user->setDescription($pass);
            $hashedPassword = $this->passwordHasher->hashPassword(
                $user,
                $pass
            );
            $user->setPassword($hashedPassword);
            $this->entityManager->persist($user);
            $this->entityManager->flush();
        }
    }
}

TestHashPasswordCommand.php

<?php

namespace App\Command;

use App\Entity\User;
use App\TestHashPassword;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class TestHashPasswordCommand extends Command
{
    protected static $defaultName = 'test-hash-password';
    protected static $defaultDescription = 'Add a short description for your command';

    protected function configure(): void
    {
        $this
            ->addArgument('arg1', InputArgument::OPTIONAL, 'Argument description')
            ->addOption('option1', null, InputOption::VALUE_NONE, 'Option description')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $arg1 = $input->getArgument('arg1');

        if ($arg1) {
            $io->note(sprintf('You passed an argument: %s', $arg1));
        }

        if ($input->getOption('option1')) {
            // ...
        }

        $io->success('You have a new command! Now make it your own! Pass --help to see your options.');
        $foobar = new TestHashPassword();  // 2 parameters necessary
        $foobar->hashPassword();
//        TestHashPassword::hashPassword(); // will give an error saying I cannot use $this there
        return Command::SUCCESS;
    }
}

我在命令 CLI 中运行: php .\bin\console test-hash-password

您也应该能够为您的命令使用自动装配(使用默认的 services.yaml 配置)。

而不是创建一个new TestHashPassword(); ,使用自动布线将其作为服务注入。

在您的命令中添加__construct

use App\TestHashPassword;
class TestHashPasswordCommand extends Command
{
    protected $testHashPassword;
    protected static $defaultName = 'test-hash-password';
    protected static $defaultDescription = 'Add a short description for your command';

    public function __construct(TestHashPassword $testHashPassword)
    {
        $this->testHashPassword = $testHashPassword;
    }
    

然后将它与您的初始化变量一起使用:

$this->testHashPassword->hashPassword();

PS:为什么会有parent::__construct(); 如果它不扩展类,在您的服务构造函数中?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM