Skip to content

注册命令

查看Application类的add方法,

php
public function add(Command $command)
{
    $this->init();

    $command->setApplication($this);

    if (!$command->isEnabled()) {
        $command->setApplication(null);

        return null;
    }

    if (!$command instanceof LazyCommand) {
        // Will throw if the command is not correctly initialized.
        $command->getDefinition();
    }

    if (!$command->getName()) {
        throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', get_debug_type($command)));
    }
    // 重点看这行,将命令的名称以及对应实现添加到命令属性中
    $this->commands[$command->getName()] = $command;

    foreach ($command->getAliases() as $alias) {
        $this->commands[$alias] = $command;
    }
    return $command;
}

打印配置的命令数组,打开第一个/vendor/hyperf/server/src/Command/StartServer.php命令类, ![](image https://oss.xiaokeaii.top/2024/start.png)

我们可以发现,在父类的构造方法中,会将name赋值给该命令类的成员变量,之后通过getName方法获取命令的名称

php
public function __construct(private ContainerInterface $container)
{
  parent::__construct('start');
  $this->setDescription('Start hyperf servers.');
}
// StartServer的父类的构造方法
public function __construct(?string $name = null)
{
  $this->definition = new InputDefinition();
  //...
  if (null !== $name) {
      $this->setName($name);
  }
  //...
}

public function getName(): ?string
{
  return $this->name;
}