博文記錄
PHP 2019-05-29 11:55:07 859 0

同步返回值

// 待补充

异步回调/匿名函数

以下主要为解决接口文件异步回调时,所传的匿名函数参数无法和调用者保持一致。

即通过新建回调参数类,来实现定义标准返回值,使得类内部和外部调用者能保持统一的返回参数。

定义 PHP 返回值规范接口文件

ClosureCallback.php


use Closure;

class ClosureCallback
{
    protected $callback = null;

    public function __construct(Closure $callback)
    {
        $this->callback = $callback;
    }

    /**
     * @param string $file
     * @param int $time
     * @param bool $complete
     * @return mixed
     */
    public function handle(string $file, int $time, bool $complete)
    {
        // TODO: Implement handle() method.
        return call_user_func_array($this->callback, func_get_args());
    }

}

Storage 主要类

Storage.php


use ClosureCallback as InterfaceCallback;

class Storage{

    /**
     * @param array $paths
     * @param array $field
     * @param InterfaceCallback $callback
     * @return mixed
     */
    public function putFilesByField(array $paths, array $field, InterfaceCallback $callback)
    {
        // TODO: Implement putFilesByField() method.
        $time = 0;
        foreach($paths as $path){
            $singleTime = rand(1, 99);
            $time += $singleTime;
            $callback->handle($path, $singleTime, false);
        }
        $callback->handle('', $time, true);
    }

}

调用示例

实例化接口回调,参数标准均在 ClosureCallback.php 的 handle 方法中统一定义。

        $Storage = new Storage;
        $Storage->putFilesByField($files, $fields, new InterfaceCallback(function (string $file, int $time, bool $completed) use($output) {
            if ($completed === 1 || $completed === true) {
                $output->writeln(sprintf('<info>全部文件导入完成,耗时:%s</info>', $time));
            } else {
                $output->writeln(sprintf('<info>%s 导入成功, 耗时:%s</info>', $file, $time));
            }
        }));
media iamge
StudioEIM - 冒险者讲习所
0:00