首页  >  文章  >  php教程  >  PHP yield 异步操作结合同步业务代码例子

PHP yield 异步操作结合同步业务代码例子

PHP中文网
PHP中文网原创
2016-05-23 17:09:312701浏览

<?php
/*
 * yield 异步操作结合同步业务代码例子
 * @author Corz*/
//业务同步代码
function syncCode()
{
    var_dump((yield [&#39;dns&#39;, &#39;www.baidu.com&#39;]));
    var_dump((yield [&#39;lag&#39;, 200]));
    var_dump((yield [&#39;dns&#39;, &#39;www.taobao.com&#39;]));
    var_dump((yield [&#39;sql&#39;, &#39;show tables&#39;]));
}
//异步调用器
function asyncCaller(Generator $gen)
{
    $r = $gen->current();
    if (isset($r)) {
        switch ($r[0]) {
            case &#39;sql&#39;:
                AsyncMysql::getInstance()->query($r[1], 
                    function ($retval) use($gen) {
                        $gen->send($retval);
                        asyncCaller($gen);
                    });
                break;
            case &#39;dns&#39;:
                swoole_async_dns_lookup($r[1], 
                    function ($host, $ip) use($gen) {
                        $gen->send([$host, $ip]);
                        asyncCaller($gen);
                    });
                break;
            case &#39;lag&#39;:
                swoole_timer_after($r[1], 
                    function () use($gen, $r) {
                        $gen->send(&#39;lag &#39; . $r[1] . &#39;ms&#39;);
                        asyncCaller($gen);
                    });
                break;
            default:
                $gen->send(&#39;no method&#39;);
                asyncCaller($gen);
                break;
        }
    }
}

asyncCaller(syncCode());

/**
 * 异步mysql类
 */
class AsyncMysql
{

    /**
     * @var mysqli
     */
    protected $db = null;

    /**
     * @var callable
     */
    protected $callable = null;

    public static function getInstance()
    {
        static $instance = null;
        return isset($instance) ? $instance : ($instance = new self());
    }

    public function __construct()
    {
        $this->db = new mysqli(&#39;127.0.0.1&#39;, &#39;root&#39;, &#39;123456&#39;, &#39;mysql&#39;);
        swoole_event_add(swoole_get_mysqli_sock($this->db), [$this, &#39;onQuery&#39;]);
    }

    public function onQuery($db_sock)
    {
        $res = $this->db->reap_async_query();
        call_user_func($this->callable, $res->fetch_all(MYSQLI_ASSOC));
    }

    /**
     * @param string    $sql
     * @param callable  $callable
     */
    public function query($sql, callable $callable)
    {
        $this->callable = $callable;
        $this->db->query($sql, MYSQLI_ASYNC);
    }
}

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn