Symfony3.4 自定义命令
Symfony3.4 custom command
我正在尝试创建一个个人命令来更改数据库中的数据。我可以直接用 "SELECT *" 来做...但是 Symfony 说好的方法是创建一个命令来应用数据库中的更改等...所以这就是我面临的问题:
当我重写默认的 __construct 方法时,命令不会被 Symfony 自动注册,这意味着 Symfony 会忽略它。当我删除构造函数时,我的命令有效,但我只是从 $entitymanager 中得到 null(这是逻辑,因为我没有向 entitymanager 中放入任何内容?)。
请问有人能给我解决方案吗?抱歉我的英语不好,谢谢你的帮助:)
So here is my code for the command
parent::__construct
应该始终是第一行。
移动这条线,它应该可以正常工作。
{
parent::__construct();
$this->entityManager = $entityManager;
}
Symfony 的版本?
但是尝试这样做:
use Symfony\Component\Console\Command\Command;
[...]
class CreateUserCommand extends Command
{
protected static $defaultName = 'app:create-user';
/**
* @var EntityManager
*/
private $entityManager;
public function __construct(
EntityManager $entityManager,
string $name = null
) {
parent::__construct($name);
$this->entityManager = $entityManager;
protected function configure()
{
parent::configure();
[...]
}
protected function execute(InputInterface $input, OutputInterface $output)
{
[...]
}
}
您需要自动装配 EntityManagerInterface $entityManager 而不是 EntityManager 并确保自动装配已启用,如果没有,您需要在 service.yml
Here another alternative to use entityManager in your 3.4 since autowiring is not as good as 4.0 and above
`class CreateUserCommand extends ContainerAwareCommand
{
protected function execute(InputInterface $input, OutputInterface $output)
{
$entityManager = $this->getContainer()->get('doctrine')->getManager();
}
}
`
我正在尝试创建一个个人命令来更改数据库中的数据。我可以直接用 "SELECT *" 来做...但是 Symfony 说好的方法是创建一个命令来应用数据库中的更改等...所以这就是我面临的问题:
当我重写默认的 __construct 方法时,命令不会被 Symfony 自动注册,这意味着 Symfony 会忽略它。当我删除构造函数时,我的命令有效,但我只是从 $entitymanager 中得到 null(这是逻辑,因为我没有向 entitymanager 中放入任何内容?)。
请问有人能给我解决方案吗?抱歉我的英语不好,谢谢你的帮助:)
So here is my code for the command
parent::__construct
应该始终是第一行。
移动这条线,它应该可以正常工作。
{
parent::__construct();
$this->entityManager = $entityManager;
}
Symfony 的版本?
但是尝试这样做:
use Symfony\Component\Console\Command\Command;
[...]
class CreateUserCommand extends Command
{
protected static $defaultName = 'app:create-user';
/**
* @var EntityManager
*/
private $entityManager;
public function __construct(
EntityManager $entityManager,
string $name = null
) {
parent::__construct($name);
$this->entityManager = $entityManager;
protected function configure()
{
parent::configure();
[...]
}
protected function execute(InputInterface $input, OutputInterface $output)
{
[...]
}
}
您需要自动装配 EntityManagerInterface $entityManager 而不是 EntityManager 并确保自动装配已启用,如果没有,您需要在 service.yml
Here another alternative to use entityManager in your 3.4 since autowiring is not as good as 4.0 and above
`class CreateUserCommand extends ContainerAwareCommand
{
protected function execute(InputInterface $input, OutputInterface $output)
{
$entityManager = $this->getContainer()->get('doctrine')->getManager();
}
}
`