Feeds:
文章
迴響

Archive for 2014 年 05 月

PHP5.3 – PHP5.4 模擬 finally

PHP5.5 將提供 try..catch.finally… 不過之前版本無緣享用

[1] 提供 __invoke + closure 方式模擬 finally, 程式片端摘錄如下

class FinallyEmulator
{
    public function __construct($callable)
    {
        if (!is_callable($callable))
            throw new ErrorException('Ooops, bad callable.');
        $this->callable = $callable;
    }

    public function __destruct()
    {
        $this->invoke();
    }

    public function __invoke()
    {
        $this->invoke();
    }

    private function invoke()
    {
        if ($this->callable)
        {
            $callable = $this->callable;
            $this->callable = NULL;
            call_user_func($callable);
        }
    }

    private $callable;
}

/**
 * Note that return value of $callable is totally ignored.
 */
function finally($callable)
{
    return new FinallyEmulator($callable);
}
class A
{
    public function doSomething()
    {
        $my_resource = open_my_resource();
        $finally = finally(function () use ($my_resource)
        {
            free_my_resource($my_resource);
        });
        try
        {
            $result = use_my_resource($my_resource);
        }
        catch (Exception $e)
        {
            fprintf(STDERR, "Error: %s\n", $e->getMessage());
            throw $e;
        }
        $finally();
        return $result;
    }
}

參考資料
[1] https://athos.blogs.balabit.com/2011/02/try-catch-finally-in-php/

廣告

Read Full Post »

VirtualBox 掛載 .img

本來想用 OSFMount 虛擬成 USB 開機,結果他只能產生一個磁碟,但並沒有完整虛擬一個裝置,因此Virtualbox 抓不到… 所以,改用轉檔方式…

 

1. .img 轉 .vdi

C:\Program Files\Oracle\VirtualBox>VBoxManage.exe convertfromraw -format VDI d:\usb.img d:\usb.vdi

2. 掛載 vdi

20140506-01

3. 測試

20140506-02

 

 

Read Full Post »