定制 mano/generator-plus 二次开发

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

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

mano/generator-plus

Composer 安装命令:

composer require mano/generator-plus

包简介

GeneratorPlus is a PHP library that wraps and extends the functionality of generators, providing enhanced features for more powerful and flexible generator usage.

README 文档

README

GeneratorPlus is a wrapper around the native Generator class that provides additional methods for more control over the iteration process.

Main Purposes

1. Fix the problem with calling send method in a foreach loop

In native PHP, calling the send method inside a foreach loop is problematic because it advances the generator to the next yield, disrupting the loop's iteration. GeneratorPlus solves this issue with the sendInForeach method, which ensures you can send values into the generator without moving to the next yield, maintaining the integrity of the loop.

Problem Example: In this example, calling send inside the foreach loop causes the generator to advance to the next yield statement, disrupting the loop and skipping iterations, leading to unintended behavior.

function getGenerator(): \Generator {
    $sent = [];
    $sent[] = yield 1;
    $sent[] = yield 2;
    $sent[] = yield 3;
    $sent[] = yield 4;
    $sent[] = yield 5;

    return $sent;
}

$generator = getGenerator();

$items = [];
foreach ($generator as $item) {
    $items[] = $item;
    $generator->send(9); // This advances the generator, skipping iterations
}

var_dump($items); // Outputs [1, 3, 5];
var_dump($generator->getReturn()); // Outputs [9, null, 9, null, 9];

2. Provide mechanism to communicate with the generator caller during the Loop

Unlike the native getReturn method, which only allows communication at the end of the generator's execution, GeneratorPlus provides a mechanism to communicate with the generator caller during the loop. This reverse communication allows for more dynamic interactions and event handling within the generator lifecycle.

Installation

You can install GeneratorPlus via Composer:

composer require mano/generator-plus

Usage

Creating a GeneratorPlus Instance

To create an instance of GeneratorPlus, use the createFromCallable method, which takes a closure that returns a generator. There are two reasons why a closure must be used instead of creating it directly from the generator:

  • Generators cannot be cloned, so using a closure ensures that the original generator is not modified.
  • The EventDispatcher must be passed to the generator.
use Mano\GeneratorPlus\GeneratorPlus;
use Mano\GeneratorPlus\EventDispatcher\GeneratorEventDispatcher;

$generatorPlus = GeneratorPlus::createFromCallable(function(GeneratorEventDispatcher $eventDispatcher) {
    yield 1;
    $sent = yield 2;

    if ($sent === 'foo') {
        yield 7;
    }

    $eventDispatcher->dispatch(new MyCustomEvent('There is just one item left!'));

    yield 3;

    return 'bar';
});

Attaching Events

You can attach events to the generator lifecycle using the attachEvent method:

use Mano\GeneratorPlus\EventDispatcher\GeneratorPlusEvent;

$generatorPlus->attachEvent(MyCustomEvent::class, function(MyCustomEvent $event) {
    echo "Oh my! The generator wants something! " . $event->getMessage();
});

Iterating with sendInForeach

The sendInForeach method allows you to send values into the generator within a foreach loop without disrupting the loop's iteration:

function getGenerator(): \Generator {
    $sent = [];
    $sent[] = yield 1;
    $sent[] = yield 2;
    $sent[] = yield 3;
    $sent[] = yield 4;
    $sent[] = yield 5;

    return $sent;
}

$generator = getGenerator();

$items = [];
foreach ($generator as $item) {
    $items[] = $item;
    $generator->sendInForeach(9); // This does not advance the generator
}

var_dump($items); // Outputs [1, 2, 3, 4, 5];
var_dump($generator->getReturn()); // Outputs [9, 9, 9, 9, 9];

Real-World Example

When dealing with batch processing in Doctrine, GeneratorPlus can come in handy. Usually, you need to flush and clear the entity manager after some batch size to prevent memory issues. Employing the generator's event dispatcher can convey the message that one chunk has been processed to fire an event that clears the entity manager. If you clear the entity manager in the middle of a batch, residual objects would be detached from the manager, leading to errors.

class SomeRepository
{
	public function getSomeEntityBasedOnCondition(GeneratorEventDispatcher $eventDispatcher = null)
	{
		$counter = 0;

		while (true) {
			$qb = $this->entityManager->createQueryBuilder()
				->where('...') // select all entities that have not been updated yet
				->setMaxResults(100);

			$result = $qb->getQuery()->getResult();

			if (count($result) === 0) {
				break;
			}

			foreach ($result as $item) {
				yield $item;
				$counter++;
			}

			if($eventDispatcher !== null) {
				// let the client code know about reaching the end of the batch
				$eventDispatcher->dispatch(new MyCustomFlushEvent($counter));
			}

		}
	}
}

class SomeController
{
	public function __construct(private SomeRepository $repository)
	{
	}

	public function someAction()
	{
		$generatorPlus = GeneratorPlus::createFromCallable(function (EventDispatcher $eventDispatcher) {
			return $this->repository->getSomeEntityBasedOnCondition($eventDispatcher);
		});

		// Or use a different style if not any other arguments needed 
		// $generatorPlus = GeneratorPlus::createFromCallable([$this->repository, 'getSomeEntityBasedOnCondition']);

		$generatorPlus->attachEvent(MyCustomFlushEvent::class, function (MyCustomFlushEvent $event) {
			// flush at the end of the batch
			$this->entityManager->flush();
			if ($event->getCount() % 500 === 0) {
				// clear the entity manager
				$this->entityManager->clear();
			}
		});

		foreach ($generatorPlus as $item) {
			// some batch action
			$item->setFoo(...);
		}
	}
}

License

This project is licensed under the MIT License. See the LICENSE file for details.

Contributing

Contributions are welcome! Please submit a pull request or open an issue to discuss any changes.

mano/generator-plus 适用场景与选型建议

mano/generator-plus 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 06 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「generator」 「wrapper」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 mano/generator-plus 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mano/generator-plus 我们能提供哪些服务?
定制开发 / 二次开发

基于 mano/generator-plus 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-06-24