用于在另一个进程中运行回调的Worker线程

0.1.0 2014-07-06 22:32 UTC

This package is not auto-updated.

Last update: 2024-09-28 16:37:57 UTC


README

Worker是一个简单的库,允许用户将函数或类方法执行到单独的PHP进程中。除此之外,它还接受成功时的函数或类方法,以及错误时的函数或类方法。

许可

MIT许可下发布。完全免费供个人或商业项目使用。

要求

该库需要PHP 5.4+。

安装

在您的composer.json中,在require部分添加以下内容

{
    "require": {
        "arkanmgerges/worker": "dev-master"
    }
}

然后

php composer.phar update

或者如果您已经在系统中安装了composer,可以直接调用而不需要PHP

composer update

教程

1. 使用Worker

Use Worker\Worker

2. 使用匿名函数

$worker = new Worker(
    // Here you can provide your main callback
    function($arg1 = '', $arg2 = '') {
        file_put_contents('result.txt', $arg1 . $arg2);
    },
    // The second one is used when main callback has completed successfully
    function() {
        file_put_contents('success.txt', 'success');
    },
    // If an exception has happened in the main callback then this callback will be called with an error message
    function($e) {
        file_put_contents('error.txt', 'error');
    }
);

// Start the worker, and pass 2 arguments to the main callback. It is also possible to pass more arguments
$worker->start('first arg', 'second arg');

3. 使用类对象方法

class SomeClass
{
    public function method($arg1, $arg2, $arg3)
    {
        file_put_contents('result.txt', $arg1 . $arg2 . $arg3);
    }
};

然后,在某个地方

$object = new SomeClass();
// Pass array, first item is the object and second item is the name of the class method
$worker = new Worker([$object, 'method']);
// Start worker and send 3 arguments
$worker->start('from', ' object method', ', this is nice');

4. 使用类静态方法

class SomeClass
{
    public static function method($arg1, $arg2, $arg3)
    {
        file_put_contents('result.txt', $arg1 . $arg2 . $arg3);
    }
};

然后在某个地方

$worker = new Worker(__NAMESPACE__ . '\SomeClass::method');
$worker->start('from', ' class method', ', nice');