我想從命令列運行我的類中的函式 hashPassword。我發現了很多關于這個主題的帖子,但我從來沒有成功讓它明顯運行。
我應該如何運行它?
<?php
namespace App;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
class TestHashPassword
{
private $entityManager;
private $passwordHasher;
public function __construct(EntityManagerInterface $em,UserPasswordHasherInterface $passwordHasherInterface){
$this->entityManager = $em;
$this->passwordHasher = $passwordHasherInterface;
parent::__construct();
}
public function hashPassword(){
$userAll = $this->entityManager
->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();
}
}
}
我試過了 :
php -r "include 'App\TestHashPassword.php'; TestHashPassword::hashPassword();"
php -r "include 'TestHashPassword.php'; TestHashPassword::hashPassword();"
php "require 'TestHashPassword.php'; hashPassword();"
php -r "require 'TestHashPassword.php'; hashPassword();"
...
我也沒有要求或包括測驗。嘗試使用另一個呼叫該函式的檔案,但沒有任何效果。
uj5u.com熱心網友回復:
看看建構式,這個類使用了實作 EntityManagerInterface 和 UserPasswordHasherInterface 介面的依賴,如果你想在 Symfony 背景關系之外使用 TestHashPassword 類,你應該創建這些依賴的實體。
但是,您可能想要使用 Symfony DI 容器。然后讓我們通過以下方式創建一個控制臺命令:
php .\bin\console make:command test-hash-password
接下來,將 hashPassword 方法呼叫放在執行部分:
<?php
namespace App\Command;
use App\TestHashPassword;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'test-hash-password',
description: 'Add a short description for your command',
)]
class TestHashPasswordCommand extends Command
{
public function __construct(
TestHashPassword $testHashPassword,
)
{
parent::__construct();
$this->testHashPassword = $testHashPassword;
}
protected function configure(): void
{
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$this->testHashPassword->hashPassword();
$io->success('The hashPassword method called successfully!');
return Command::SUCCESS;
}
}
現在您可以執行新命令:
php .\bin\console test-hash-password
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/475561.html
