`Fiber` 命令行加载动画

Fiber 更加方便异步, 比 yield 更加便于理解和操作 :grinning:

  • 代码参考
    public function run(Input $input, Output $output): void
    {
        if (strpos(PHP_VERSION, '8.1') !== 0) {
            $output->writeLine('需要 8.1 版本以上!!!');
            return;
        }

        //doSomething
        //光标隐藏/恢复
        $hideCursor = $this->hideCursor();

        $output->write("\033[s");
        $output->write('loading ');

        //加载进度
        $dotLoad = $this->dotLoader();
        $dotLoad->start(1);

        for ($i = 1; $i <= 100; $i++) { 
            # code...
            usleep(100000);
            $dotLoad->resume($i%100);
        }
        $output->writeLine('finished !!!');

        $hideCursor->resume();
    }

    /**
     * 协程加载动画
     *
     * @return \Fiber
     */
    private function dotLoader(): \Fiber
    {
        return new \Fiber(function () {
            $jump = '·';
            $load = ['.', '.', '.', '.', '.', '.', '.', '.','.'];
            echo "\033[32;1m 00% " . implode('', $load) . "\033[0m";
            while(true) {
                for ($i=0; $i < 9; $i++) {
                    $temp = $load;

                    $temp[$i] = $jump;
                    $tmpStr = "\033[32;1m {step}". implode('', $temp) . "\033[0m";
                    $step = \Fiber::suspend();
                    if ( $step === 0) {
                        break 2;
                    } 
                    echo "\033[14D";
                    echo str_replace('{step}', sprintf('%02d%% ', $step), $tmpStr);
                }
            }
            echo "\033[u\033[K";
        });
    }

    /**
     * 协程光标隐藏/恢复
     *
     * @return \Fiber
     */
    private function hideCursor(): \Fiber
    {
        $f = new \Fiber(function () {
            echo "\033[?25l";
            \Fiber::suspend();
            echo "\033[?25h";
        });
        $f->start();
        return $f;
    }
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 3
porygonCN

优秀啊:

2年前 评论
DonnyLiu

:cow:

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!