定制 jced-artem/leak-safe-generator 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

jced-artem/leak-safe-generator

Composer 安装命令:

composer require jced-artem/leak-safe-generator

包简介

Generator wrapper to prevent memory leaks

README 文档

README

Install

composer require jced-artem/leak-safe-generator

If you want to prevent memory leaks when you use generators with handlers and you bored to use try..finally constructions - this class could help.

Example

function parsePages() {
    $ch = curl_init();
    // ... some options
    while ($condition) {
        yield curl_exec($ch);
    }
    curl_close($ch);
}

foreach (parsePages() as $page) {
    if ($someCondition) {
        break;
    }
    // ...
}

Problem

If you break loop before get all yields you will have not closed handler $ch and this can cause memory leaks.

Solution

function parsePages() {
    $ch = curl_init();
    // ... some options
    try {
        $finished = false;
        while ($condition) {
            yield curl_exec($ch);
        }
        $finished = true;
    } finally {
        // close anyway
        curl_close($ch);
        if ($finished) {
            // do something if reached last element
        } else {
            // do something on break
        }
    }
}

New problem

This code isn't usable if you make several generators

New solution

$lsg = new LeakSafeGenerator();
$lsg
    ->init(function() {
        $this->ch = curl_init();
        // ... some options
        while ($condition) {
            yield curl_exec($this->ch);
        }
    })
    ->onInterrupt(function() {
        // do something on break
    })
    ->onComplete(function() {
        // do something if reached last element
    })
    ->onFinish(function() {
        curl_close($this->ch);
    })
;
foreach ($lsg->getGenerator() as $page) {
    if ($someCondition) {
        break;
    }
    // ...
}

or shorter version

$lsg = new LeakSafeGenerator(
    function() {
        $this->ch = curl_init();
        // ... some options
        while ($condition) {
            yield curl_exec($this->ch);
        }
    },
    function() {
        curl_close($this->ch);
    }
);

And you don't need to create additional functions/methods and write try..finally constructions for each generator.

统计信息

  • 总下载量: 16
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2016-12-13

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固