danibrutal/forker

在PHP中执行并行任务的结构化、安全且最简单的方式

v1.1.0 2014-11-08 17:24 UTC

This package is not auto-updated.

Last update: 2024-09-28 15:34:12 UTC


README

Build Status Latest Stable Version

概述

在PHP中执行并行任务的结构化、安全且最简单的方式。

代码示例

<?php
/**************************************************
 * Example: Retrieving the city-weather using external api
 * Usage  : php examples/demo.api.weather.php 
 * Storage: File
 **************************************************/
require 'vendor/autoload.php';

use Forker\Forker;
use Forker\Storage\FileStorage;

$allCitiesWeather = "";

$urlApiWeather = "http://api.openweathermap.org/data/2.5/weather?q=%s&mode=xml";

$myTasks = array(
  'madrid'    => sprintf($urlApiWeather, 'Madrid'),
  'london'    => sprintf($urlApiWeather, 'London'),
  'new-york'  => sprintf($urlApiWeather, 'NewYork'),
  'barcelona' => sprintf($urlApiWeather, 'barcelona'),
  'lisboa'    => sprintf($urlApiWeather, 'lisboa'),
  'iasi'      => sprintf($urlApiWeather, 'iasi'),
);

// a way to keep our data
$storageSystem = new FileStorage;
$numberOfSubTasks = 6;

$forker = new Forker($storageSystem, $myTasks, $numberOfSubTasks);

$forker->fork(function($city, $url,  $emit) {
  echo "Retrieving weather in $city\n";
  
  $contents = file_get_contents($url);
  $emit($city, $contents);
});

$allCitiesWeather = $forker->fetch();

var_dump($allCitiesWeather);

动机

有时我们必须处理大量数据。最近,数据量越来越大,根本无法按顺序工作。

例如,厨房里有两位厨师和一根非常大的胡萝卜。好吧,我们希望两位工人不要互相等待。那么,为什么我们不把胡萝卜分成两半,让他们各自处理一部分呢?

这样,两位厨师可以同时工作,我们很快就能吃上晚餐!太棒了,不是吗?

因此,目的是创建一种敏捷且封装的方法,将任务分割成多个子任务并行执行。

安装

使用composer

  "require": {
        "danibrutal/forker": "dev-master"
    }

API参考

您可以在这里查看API;

创建自己的StorageSystem

我们遵循TDD方法,因此开发新系统非常简单

1. 创建自己的存储系统,遵循StorageSystem接口的签名

/**
   * @param key
   * @param value
   * @return bool
   */
  public function store($key, $value);

  /**
   * @param key
   * @return value | false
   */
  public function get($key);

  /**
   * @return array $tasks
   */
  public function getStoredTasks();

  /**
   * @return bool
   */
  public function cleanUp();

2. 创建一个测试

<?php
use Forker\Storage\ArrayStorage;
require_once 'BaseStorageTest.php';

class ArrayStorageTest extends BaseStorageTest
{
    protected function getSystemStorage()
    {        
        return new ArrayStorage();        
    }
}

难吗?

3. 然后,键入phpunit,您可以查看要解决的3个错误

There were 4 failures:

1) ArrayStorageTest::testWeCanGetASimpleStoredValue
Failed asserting that null matches expected 'value'.

2) ArrayStorageTest::testWeCanSToreValues
Failed asserting that null is true.

3) ArrayStorageTest::testIcanGetAllMyStoredTasks
Failed asserting that a NULL is not empty.

4) ArrayStorageTest::testWeCanCleanUpAllPreviousTasks
Failed asserting that a NULL is not empty.

4. 只需解决这些错误。创建您的实现,您就完成了!简单且有趣:)

贡献者

请随意合作。分支项目并检查[问题][2]。我们还有很多工作要做!

许可证

MIT