在Symfony中,可以通过将共享的代码提取到一个基础命令类中,然后让其他具体的命令类继承该基础类来避免重复代码。
以下是一个示例:
首先,创建一个基础命令类,例如BaseCommand
:
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
class BaseCommand extends Command implements ContainerAwareInterface
{
use ContainerAwareTrait;
protected function configure()
{
// 设置命令名称和描述等
$this
->setName('base:command')
->setDescription('This is a base command.')
// 添加通用的选项和参数
->addOption('option', null, InputOption::VALUE_OPTIONAL, 'Option description')
->addArgument('argument', InputArgument::OPTIONAL, 'Argument description');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// 具体的命令逻辑
// 使用$this->container获取依赖的服务
}
}
然后,创建其他具体的命令类,例如CommandA
和CommandB
,它们继承自BaseCommand
:
namespace App\Command;
class CommandA extends BaseCommand
{
protected function configure()
{
parent::configure();
// 可以在这里添加特定于CommandA的选项和参数
$this
->setName('command:a')
->setDescription('This is command A.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
// 具体的CommandA逻辑
}
}
class CommandB extends BaseCommand
{
protected function configure()
{
parent::configure();
// 可以在这里添加特定于CommandB的选项和参数
$this
->setName('command:b')
->setDescription('This is command B.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
parent::execute($input, $output);
// 具体的CommandB逻辑
}
}
现在,你可以像使用任何其他Symfony命令一样使用CommandA
和CommandB
。它们都继承了BaseCommand
的通用选项和参数,并且可以通过调用$this->container
来访问共享的依赖关系。
使用这种方法,你可以避免在多个具有相同依赖关系的命令类中重复编写相同的代码,提高了代码的可维护性和可扩展性。
上一篇:避免重复代码,应该使用常量。
下一篇:避免重复但不使用distinct