跳到内容

Cursor Helper

编辑此页

Cursor 允许您在控制台命令中更改光标位置。 这允许您在输出的任何位置写入内容

A command outputs on various positions on the screen, eventually drawing the letters "SF".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// src/Command/MyCommand.php
namespace App\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Cursor;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class MyCommand extends Command
{
    // ...

    public function execute(InputInterface $input, OutputInterface $output): int
    {
        // ...

        $cursor = new Cursor($output);

        // moves the cursor to a specific column (1st argument) and
        // row (2nd argument) position
        $cursor->moveToPosition(7, 11);

        // and write text on this position using the output
        $output->write('My text');

        // ...
    }
}

使用光标

移动光标

有几种方法可以控制命令光标的移动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// moves the cursor 1 line up from its current position
$cursor->moveUp();

// moves the cursor 3 lines up from its current position
$cursor->moveUp(3);

// same for down
$cursor->moveDown();

// moves the cursor 1 column right from its current position
$cursor->moveRight();

// moves the cursor 3 columns right from its current position
$cursor->moveRight(3);

// same for left
$cursor->moveLeft();

// move the cursor to a specific (column, row) position from the
// top-left position of the terminal
$cursor->moveToPosition(7, 11);

您可以使用以下方法获取当前命令的光标位置

1
2
3
$position = $cursor->getCurrentPosition();
// $position[0] // columns (aka x coordinate)
// $position[1] // rows (aka y coordinate)

清除输出

光标还可以清除屏幕上的一些输出

1
2
3
4
5
6
7
8
9
10
11
// clears all the output from the current line
$cursor->clearLine();

// clears all the output from the current line after the current position
$cursor->clearLineAfter();

// clears all the output from the cursors' current position to the end of the screen
$cursor->clearOutput();

// clears the entire screen
$cursor->clearScreen();

您还可以利用光标上的 show()hide() 方法。

本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。
目录
    版本