{"id":495,"date":"2024-02-28T20:57:52","date_gmt":"2024-02-28T19:57:52","guid":{"rendered":"https:\/\/extendsclass.com\/blog\/?p=495"},"modified":"2024-02-04T16:46:24","modified_gmt":"2024-02-04T14:46:24","slug":"exploring-php-generators-unleashing-creative-power-with-yield","status":"publish","type":"post","link":"https:\/\/extendsclass.com\/blog\/exploring-php-generators-unleashing-creative-power-with-yield","title":{"rendered":"Exploring PHP Generators: Unleashing creative power with yield"},"content":{"rendered":"\n<p>Generators in PHP, introduced since PHP 5.5 (that&#8217;s a while ago\u2026), leveraging the <code>yield<\/code> statement, are often underestimated. This article aims to unveil the creative power of <code>yield<\/code> and demonstrate how to use it to optimize the efficiency of your PHP programs. Generators go beyond mere value generation; they enable efficient iteration (A Generator is an Iterator). To grasp the workings of generators, let&#8217;s delve into their mechanism and explore the central role of <code>yield<\/code>.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_47_1 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"ez-toc-toggle-icon-1\"><label for=\"item-69ed04035da30\" aria-label=\"Table of Content\"><span style=\"display: flex;align-items: center;width: 35px;height: 30px;justify-content: center;direction:ltr;\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/label><input  type=\"checkbox\" id=\"item-69ed04035da30\"><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/extendsclass.com\/blog\/exploring-php-generators-unleashing-creative-power-with-yield\/#Introduction\" title=\"Introduction++\">Introduction++<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/extendsclass.com\/blog\/exploring-php-generators-unleashing-creative-power-with-yield\/#Efficient_Handling_of_Large_Data_Sets\" title=\"Efficient Handling of Large Data Sets\">Efficient Handling of Large Data Sets<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/extendsclass.com\/blog\/exploring-php-generators-unleashing-creative-power-with-yield\/#Building_Processing_Pipelines\" title=\"Building Processing Pipelines\">Building Processing Pipelines<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/extendsclass.com\/blog\/exploring-php-generators-unleashing-creative-power-with-yield\/#Resource_Management_with_yield\" title=\"Resource Management with yield\">Resource Management with yield<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/extendsclass.com\/blog\/exploring-php-generators-unleashing-creative-power-with-yield\/#Retrieving_the_function%E2%80%99s_return_value\" title=\"Retrieving the function&#8217;s return value\">Retrieving the function&#8217;s return value<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/extendsclass.com\/blog\/exploring-php-generators-unleashing-creative-power-with-yield\/#Bidirectional_communication\" title=\"Bidirectional communication\">Bidirectional communication<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/extendsclass.com\/blog\/exploring-php-generators-unleashing-creative-power-with-yield\/#Conclusion\" title=\"Conclusion\">Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Introduction\"><\/span>Introduction++<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><code>yield<\/code> in PHP is used in generators to produce values incrementally. It temporarily returns a value while preserving the state of the generator function between calls, optimizing memory and performance when handling large datasets.<\/p>\n\n\n\n<p>Each invocation of <code>yield<\/code> returns a value while preserving the generator&#8217;s state between calls. The following example will output &#8220;1 2 3&#8221;:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function simpleGenerator() {\n    yield 1;\n    yield 2;\n    yield 3;\n}\n\n$generator = simpleGenerator();\n\nforeach ($generator as $value) {\n    echo $value . ' ';\n}<\/code><\/pre>\n\n\n\n<p>A generator can easily yield a key associated with a value using the double arrow:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function countryGenerator() {\n    yield 'Germany' =&gt; 1;\n    yield 'Belgium' =&gt; 2;\n    yield 'France' =&gt; 3;\n}\n\nforeach (countryGenerator() as $countryName =&gt; $id) {\n    ...\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Efficient_Handling_of_Large_Data_Sets\"><\/span><strong>Efficient Handling of Large Data Sets<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>One major advantage of using <code>yield<\/code> lies in the management of large datasets. Instead of storing the entire set in memory, employ <code>yield<\/code> to process the data on the fly.<\/p>\n\n\n\n<p>Asynchronous processing with <code>yield<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function asyncDataProcessor($data) {\n    foreach ($data as $item) {\n        yield processAsync($item);\n    }\n}<\/code><\/pre>\n\n\n\n<p>Here, <code>processAsync<\/code> could represent a time-consuming operation, and the generator enables asynchronous processing without loading the entire dataset into memory.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Building_Processing_Pipelines\"><\/span><strong>Building Processing Pipelines<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><code>yield<\/code> can be used to construct elegant processing pipelines by passing data from one generator to another.<\/p>\n\n\n\n<p>Creating a processing pipeline:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function processPipeline($data) {\n    yield from filterData($data);\n    yield from transformData($data);\n    yield from aggregateData($data);\n}<\/code><\/pre>\n\n\n\n<p>In this example, each stage of the pipeline is a generator function, allowing a clean separation of responsibilities. However, be mindful of visibility\u2026<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Resource_Management_with_yield\"><\/span><strong>Resource Management with <code>yield<\/code><\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><code>yield<\/code> can also be employed to efficiently manage resources by automatically releasing those that are no longer needed.<\/p>\n\n\n\n<p>Automatic resource release:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function resourceManager($resources) {\n    foreach ($resources as $resource) {\n        $data = loadData($resource);\n        yield $data;\n        releaseResource($resource);\n    }\n}<\/code><\/pre>\n\n\n\n<p>In this example, resources are automatically released once the associated data has been processed.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Retrieving_the_function%E2%80%99s_return_value\"><\/span>Retrieving the function&#8217;s return value<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Since PHP 7.0, it is possible to further enhance generators by retrieving a value returned by the function at the end of its execution. Remember, the basic syntax means that when calling a generator, you obtain the generated iterator, not the return value.<\/p>\n\n\n\n<p>Imagine we want to extend the generator that reads the contents of a file line by line, and additionally, we want it to count the number of empty lines in the file. How do we retrieve this count? To achieve this, we use the <code>getReturn()<\/code> method on the generated iterator:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function myGenerator() {\n    yield 1;\n    yield 2;\n    yield 3;\n    return 0;\n}\n\n$generator = myGenerator();\nforeach ($generator as $data) {\n    ...\n}\n\/\/ retrieve the result\n$result = $generator-&gt;getReturn();<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Bidirectional_communication\"><\/span>Bidirectional communication<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>It&#8217;s also possible to communicate in the other direction, from the iterator to the generator. Simply use the <code>send()<\/code> method of the iterator to send data back, which can be accessed in the generator by retrieving the &#8220;return value&#8221; of the <code>yield<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function myGenerator() {\n    $res = yield 1;\n    if ($res === false)\n       break;\n    ...\n}\n\n$generator = myGenerator();\nforeach ($generator as $data) {\n    ...\n    $generator-&gt;send(false); \/\/ Processing will stop\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Generators are fantastic (short, but everything is said).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Generators in PHP, introduced since PHP 5.5 (that&#8217;s a while ago\u2026), leveraging the yield statement, are often underestimated. This article aims to unveil the creative power of yield and demonstrate how to use it to optimize the efficiency of your PHP programs. Generators go beyond mere value generation; they enable efficient iteration (A Generator is [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":124,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_sitemap_exclude":false,"_sitemap_priority":"","_sitemap_frequency":""},"categories":[2],"tags":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/posts\/495"}],"collection":[{"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/comments?post=495"}],"version-history":[{"count":8,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/posts\/495\/revisions"}],"predecessor-version":[{"id":497,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/posts\/495\/revisions\/497"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/media\/124"}],"wp:attachment":[{"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/media?parent=495"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/categories?post=495"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/extendsclass.com\/blog\/wp-json\/wp\/v2\/tags?post=495"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}