<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alin Pintilie on Medium]]></title>
        <description><![CDATA[Stories by Alin Pintilie on Medium]]></description>
        <link>https://medium.com/@alin.pintilie?source=rss-a55d872292e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ipVxcX2jf5eYNN1DrTui6w.jpeg</url>
            <title>Stories by Alin Pintilie on Medium</title>
            <link>https://medium.com/@alin.pintilie?source=rss-a55d872292e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:03:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alin.pintilie/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ A HEROIC PROBLEM in Organizations]]></title>
            <link>https://medium.com/@alin.pintilie/dr-bruce-cameron-director-of-the-system-architecture-group-at-mit-was-asked-in-an-6fc5358b05c5?source=rss-a55d872292e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fc5358b05c5</guid>
            <dc:creator><![CDATA[Alin Pintilie]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 05:06:21 GMT</pubDate>
            <atom:updated>2025-07-14T05:09:01.816Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tOY_6wrPuSPiedP8" /><figcaption>Photo by <a href="https://unsplash.com/@tkristin?utm_source=medium&amp;utm_medium=referral">TK</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Dr. Bruce Cameron (Director of the System Architecture Group at MIT) was asked in an [interview](<a href="https://youtu.be/2XTPKNCN4q4?t=3050">https://youtu.be/2XTPKNCN4q4?t=3050</a>) if he had any advice for dealing with the <strong>problem of “heroes”.</strong></p><p>Heroes? Who or what are they?<br>To be honest, this was the **first time I’d heard about this issue.** But the more I read, the more I realized how real (and dangerous) it can be.</p><p><strong>Heroes are people who make themselves indispensable — but in doing so, they hold the company back from growing. </strong><br>The presence of such individuals often leads to what’s known as the “[hit by the bus](<a href="https://www.techminers.com/knowledge/bus-factor-in-technical-departments">https://www.techminers.com/knowledge/bus-factor-in-technical-departments</a>)&quot; risk.</p><p>It turns out this is not just an isolated issue but can be <strong>a systemic problem within organizations</strong>, and it’s certainly more widespread (and studied) than I initially thought.</p><p>We often hear about “<strong>hero culture</strong>”, which refers to ”<strong>an organization, or a functional area within it, that relies on a small group of hard-working, highly talented ‘heroes’ to keep things running — through sheer willpower, skill, and personal sacrifice.</strong>”</p><p>The real problems emerge when the company reaches a <strong>strategic inflection point</strong>. A major shift in the business environment (such as increased competition, regulatory changes, or economic pressures) that requires the organization to adapt quickly or risk decline.</p><p>In hero-oriented organizations, <strong>as the business grows, it requires more heroes to sustain it </strong>— a model that quickly becomes unsustainable.</p><p>This is not just a startup problem. Many large, mature companies also struggle to get past inflection points. Instead of evolving into process-driven, scalable operations, they remain trapped in hero-mode.</p><p>Once this issue is identified, “optimally, the catalyst for change in a mature organization stuck in hero culture is the board of directors and senior management team.” <br>But the solutions are not silver bullets or mass layoffs. They require pragmatic, sustained efforts at all levels of the company.</p><p>Neglecting this issue is simply too risky.</p><p>Source:</p><p><a href="https://www.techminers.com/knowledge/bus-factor-in-technical-departments">Bus factor in technical departments</a></p><p><a href="https://www.inteqgroup.com/blog/transforming-a-hero-culture">https://www.inteqgroup.com/blog/transforming-a-hero-culture</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fc5358b05c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Php generators or how to simplify iterators]]></title>
            <link>https://medium.com/@alin.pintilie/php-generators-or-how-to-simplify-iterators-17c499f6d087?source=rss-a55d872292e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/17c499f6d087</guid>
            <category><![CDATA[generator]]></category>
            <category><![CDATA[iterators]]></category>
            <category><![CDATA[laravel-collections]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <dc:creator><![CDATA[Alin Pintilie]]></dc:creator>
            <pubDate>Sun, 26 Feb 2023 09:38:20 GMT</pubDate>
            <atom:updated>2023-02-26T09:38:20.870Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Did you know that a PHP function can return multiple times?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tendZoTCIZGGYia802c-YA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jkmills?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Josh Mills</a> on <a href="https://unsplash.com/photos/hEKSPAg8axE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Although a function typically returns only one value when called, there is another type of syntax that “simulates” multiple returns. This is called “<strong>yield</strong>”. If this term is unfamiliar to you, it was to me as well, but it’s good to know that it exists. The PHP documentation <a href="https://www.php.net/manual/en/language.generators.syntax.php">defines</a> it as “<em>the heart of a generator function</em>”. And what exactly is a generator function? The same documentation tells us that “<em>any function containing yield is a generator function</em>”. This is a fairly straightforward explanation, but the concept itself is not complicated as we will see in the following.</p><h3>Implementation of a generator function</h3><p><strong>Yield</strong></p><p>As the definition above states, in order for a function to become a generator, we need to replace the “return” statement with “yield”.</p><pre>function collectInvoices(): Generator<br>{<br>    $invoiceService = new InvoiceService();<br>    $invoices = $invoiceService-&gt;getAllInvoices();<br>    foreach ($invoices as $invoice) {<br>        //do something with invoice<br>        yield $invoice;<br>    }<br>}</pre><p><strong>Yield from</strong></p><p>Yield from<strong> </strong>also called<strong> </strong>g<em>enerator delegation</em> is another very unfamiliar statement among PHP programmer, but it is just as simple to use. It allows you to yield values from another generator, <a href="https://www.php.net/manual/en/class.traversable.php">Traversable</a> object, or array by using the yield from keyword</p><pre>function collectInvoices(): Generator<br>{<br>    $invoiceService = new InvoiceService();<br>    yield from $invoiceService-&gt;getAllInvoices();<br>}</pre><h3><strong>What is the actual benefit of a generator?</strong></h3><p><strong>Lazy functions</strong></p><p>Generators are actually Iterators. If you’re not familiar with this concept, you can take a look at the <a href="https://medium.com/@alin.pintilie/php-iterator-72f05d6940c8">article</a> where I presented it. One of the advantages of using an Iterator is <a href="https://medium.com/@alin.pintilie/lazy-loading-using-the-iterator-in-php-for-saving-90-of-memory-d421cb84f0b5">lazy loading</a>, which also applies to generators. In short, we can use generators when we want to implement a lazy loading mechanism.</p><p>Using a generator is similar to using an Iterator, meaning that we can iterate over it.</p><pre>$invoices = $invoiceService-&gt;collectInvoices();<br>foreach ($invoices as $invoice) {<br>    $storingService-&gt;store($invoice);<br>}</pre><p>When it comes to energy efficiency, a significant difference can be observed: for 41814 elements retrieved from the database by loading them all into memory, 19.14 Mb of memory were used. For the same number of elements using a generator, only 0.55 Mb of memory were used.</p><p><strong>Improve space complexity</strong></p><p>A very important aspect to mention in this case is that by using a generator, we can change the <a href="https://medium.com/karuna-sehgal/a-simplified-interpretation-of-the-time-complexity-and-space-complexity-78e4cdbb0b19">space complexity</a> (big O notation) from O(n) to O(1). This means that regardless of the size of the input, the memory allocated in memory will remain constant.</p><p><strong>Using inside Laravel Collection</strong></p><p>In Laravel, Collections are actually an Iterator used as a wrapper over an array. In the example below, we have a simple example where we initialize a Collection.</p><pre>use Illuminate\Support\Collection;<br><br>$collection = new Collection([1, 2, 3, 4]);<br>$collection-&gt;push(5);</pre><p>In the case above, an array with the respective elements will be stored in memory. Of course, this would not be a problem. However, there are situations when the number of elements that need to be stored in memory is large enough to have a significant impact.</p><p>A more concrete example would be when we want to retrieve data from a database.</p><pre>$invoices = Invoice::orderBy(&#39;invoice_date&#39;)-&gt;take(100000)-&gt;get();<br><br>foreach ($invoices as $invoice) {<br>    //do something with invoice<br>}</pre><p>To avoid problems caused by memory overload, we can use Lazy Collections. There are several ways to use lazy collection:</p><p><a href="https://laravel.com/docs/10.x/eloquent#cursors"><strong>Cursor</strong></a><strong>()</strong></p><pre>$invoices = Invoice::orderBy(&#39;invoice_date&#39;)-&gt;take(100000)-&gt;cursor();<br> <br>foreach ($invoices as $invoice) {<br>    //do something with invoice<br>}</pre><p>This method will return an object of type Illuminate\Support\LazyCollection. This method will only execute a single database query.</p><p><a href="https://laravel.com/docs/10.x/eloquent#chunking-using-lazy-collections"><strong>Lazy</strong></a><strong>()</strong></p><pre>$invoices = Invoice::orderBy(&#39;invoice_date&#39;)-&gt;take(100000)-&gt;lazy();<br> <br>foreach ($invoices as $invoice) {<br>    //do something with invoice<br>}</pre><p>Also, this method will return an object of type Illuminate\Support\LazyCollection but the mechanism behind it is similar to the one implemented by the <a href="https://laravel.com/docs/10.x/eloquent#chunking-results">chunk</a>() method, meaning it executes the query in chunks. However, since it returns a LazyCollection, this is unnoticeable, and that’s why we can interact with the results as a single stream.</p><p><strong>Yield</strong></p><pre>$invoices = LazyCollection::make(function () {<br>    $file = new SplFileObject(&#39;import_data.ndjson&#39;);<br>    $file-&gt;seek(0);<br> <br>    while ($file-&gt;valid()) {<br>        yield json_decode($file-&gt;fgets());<br>    }<br>});<br><br>foreach ($invoices as $invoice) {<br>    //do something with invoice<br>}</pre><p>To initialize a <a href="https://laravel.com/docs/10.x/collections#lazy-collections">Lazy Collection</a>, we will call the make() function which takes a generator function (that yields the values) as a parameter.</p><p>As we have seen in these examples, the generator can be a much simpler way of using the iterator. One of the most well-known benefits is the implementation of the lazy loading mechanism, which can significantly improve memory usage.</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17c499f6d087" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What do Chat GPT and IT layoffs have in common?]]></title>
            <link>https://medium.com/@alin.pintilie/what-do-chat-gpt-and-it-layoffs-have-in-common-9e187c664d4f?source=rss-a55d872292e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e187c664d4f</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[it]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[layoffs]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Alin Pintilie]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 15:05:21 GMT</pubDate>
            <atom:updated>2023-02-11T18:22:01.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*R7Pv6u0zmHdTwm2e-D_sBw.jpeg" /><figcaption>Source: <a href="https://picography.co/white-robot/">https://picography.co/white-robot/</a></figcaption></figure><h3>Layoffs</h3><p>It is already well known that the largest IT companies in the US have started a major wave of layoffs: <a href="https://layoffs.fyi/">https://layoffs.fyi/</a> . This is probably a shock to some of us, especially as it comes shortly after this industry has flourished and outperformed many other branches of the global economy that faced major problems during the pandemic.</p><p>In my opinion, the accelerated growth of businesses during the pandemic was possible due to an exacerbated demand for digital products. But the pandemic is over so do accelerated growth and the number of employees remained the same. IT was the industry that seemed untouchable, in a continuous and infinite growth, a utopian world with increasingly fine demands from employees. After all, it is a business that needs to be profitable to exist, and if costs are constant or increasing, growth in sales or productivity is needed to maintain the current profit rate.</p><h3>What about productivity?</h3><p>What I have found is that there is limited information on increased productivity in IT (except articles discussing increased productivity in remote work compared to office work). There are certain articles that discuss increased productivity in companies that have adopted different digital solutions, but that is a different matter entirely. From my perspective, we are starting to witness a paradigm shift in IT and while until now employees were valuable due to the limited resources, in the future this will change. <strong>Artificial intelligence will not replace programmers, but</strong>:</p><p><a href="https://www.youtube.com/watch?v=LXcpYfImJpA"><strong><em>Programmers will be replaced by other programmers who will use artificial intelligence.</em></strong></a></p><p>In practical terms, it’s time for productivity to increase in this industry. ChatGPT won’t replace existing programmers, but it may block access to potential employees with a lower level of experience and narrower specialization.</p><p>So, to answer the title question: <strong>What do chat GPT and IT layoffs have in common?</strong> <strong>Work productivity</strong>. To maintain your current position, it’s necessary to increase your productivity. Therefore, it is important to accept the impact of these technologies in our work environments and to transform them into a tool that can help us achieve better results with the same or even lower costs. Besides that, a new set of skills will be needed, that cannot be replaced by AI. Below will be a short list.</p><p>One of the books I’ve been thinking about lately is “<a href="https://davidepstein.com/the-range/">Range, WHY GENERALISTS TRIUMPH IN A SPECIALIZED WORLD</a>” because it deals with the problem of specialists. In IT, employees are generally specialized and if you are not, you will be encouraged to specialize in a niche (which is often a programming language) in the hope of being more productive. And if until now it was possible to be more productive in the short and medium term due to overs specialization, things will change. ChatGPT and its relatives will be able to develop a specialized function or class much faster than a programmer if they follow the instructions of another programmer who has an overview of technology, product and customer.</p><p>As someone who works in IT, I’ve discussed the impact of AI on programmers in the past, and I can confirm that all three phases described by Arthur Schopenhauer have taken place:</p><blockquote>All truth passes through three stages. First, it is ridiculed. Second, it is violently opposed. Third, it is accepted as being self-evident.</blockquote><p>We are in the final stage where everything is becoming increasingly evident, AI is here and it will stay. Of course, we can discuss specifically about ChatGPT which is still in the hype stage, but it may be followed by a period of disillusionment or the “trough of disillusionment”, but already ChatGPT 4, Bard and many others are announced.</p><blockquote>As David Epstein stated in his book “Our greatest strength is the exact opposite of narrow specialization. The broader the framework, the greater the unique contribution of the person.”</blockquote><p>So the moment is approaching when programmers will no longer be valuable just because they possess knowledge about a particular programming language, but because they will know how to choose which language and architecture are best suited for a particular problem. Skills such as creativity, communication, emotional intelligence, and analytical skills will make an employee valuable. Of course, all of these must be visible within a high level of productivity.</p><p>Although one can easily find a book for each of the above skills, the biggest problem is that these skills are not acquired by reading a book or taking a course. A longer period of acquisition and exposure to diverse information is required. Below are some of the areas where you can be better than AI:</p><p><strong>Creativity</strong></p><blockquote>According to David Epstein, “The more contexts in which something is learned, the more the learner creates abstract models, and the less the learner relies on a single example. This increases the ability to apply in an unfamiliar situation, which is the essence of creativity.”</blockquote><p>According to him, it is essential to have hobbies, involvement in projects and other types of professional activities in as many and varied areas as possible. This would lead to the stimulation of creativity and long-term learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBZGh9gKyZJLQ2bV-NqJPw.png" /></figure><p><strong>Communication</strong></p><blockquote>“The single biggest problem with communication is the illusion that it has taken place.” — George Bernard Shaw</blockquote><p>Communication can increase productivity. IT projects often involve complex and interdependent tasks, and all team members need to have a clear understanding of their roles, responsibilities, and expectations. Effective communication helps ensure that everyone is working towards a common goal and that potential issues or roadblocks can be identified and addressed before they escalate.</p><p>As long as we are human beings, we will need interpersonal communication. When you ask Chat GPT for information, there is not enough satisfying communication for the human being. It is possible to only get information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ix3qGU4q6L6S5SLaFZNXrw.png" /></figure><p><strong>Emotional Intelligence</strong></p><p>Emotional intelligence is the ability to recognize and understand your own emotions, as well as the emotions of others, and to use this information to guide your thoughts and actions. This will dictate how you communicate and interact with others, including how you respond to “threats of AI.” The father of emotional intelligence says:”</p><blockquote>“If your emotional abilities aren’t in hand, if you don’t have self-awareness, if you are not able to manage your distressing emotions, if you can’t have empathy and have effective relationships, then no matter how smart you are, you are not going to get very far. — David Goleman”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-24ajt3qJi7UpFXDXMZ3Rg.png" /></figure><p>If you’re already in this industry, the good news is that the revolution is just beginning and you can still change your orientations to gain these skills. The bad news is that you have to face change, adapt and step out of your comfort zone. If you’re from another industry, you have a very high chance of being in a similar position to those in IT.</p><p>Regardless of the degree of specialization, soon there will be an algorithm that will provide answers to problems in your area faster than you, but there will not be an algorithm soon that can innovate and communicate better than you could.</p><p>Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e187c664d4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PHP Iterator]]></title>
            <link>https://medium.com/@alin.pintilie/php-iterator-72f05d6940c8?source=rss-a55d872292e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/72f05d6940c8</guid>
            <category><![CDATA[memory-improvement]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[iterators]]></category>
            <category><![CDATA[iterator-design-pattern]]></category>
            <dc:creator><![CDATA[Alin Pintilie]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 07:59:29 GMT</pubDate>
            <atom:updated>2023-02-06T07:59:29.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjXl-cDvRqfaKj7XJ9u7BQ.jpeg" /></figure><p>If you didn’t know, yes, PHP has its own iterator functionality and if you didn’t use it you probably would be surprised to know that there are some important advantages of using it.</p><p>When it comes to parsing some data usually we are using a <em>foreach</em> statement applied on the array. The interesting point is that the <a href="https://www.php.net/manual/en/language.oop5.iterations.php">objects could also be iterated</a>. In fact <em>foreach</em> <a href="https://www.php.net/manual/en/control-structures.foreach.php">documentation</a> says that “foreach works only on arrays and objects”.</p><p>If we iterate directly on an object by default, all <a href="https://www.php.net/manual/en/language.oop5.visibility.php">visible</a> properties will be used for the iteration. We can also modify the default behavior by making an object to implement the <a href="https://www.php.net/manual/en/class.traversable.php">Traversable</a> interface. The problem is that we can not directly implement the Traversable interface but must implement either <a href="https://www.php.net/manual/en/class.iteratoraggregate.php">IteratorAggregate</a> or <a href="https://www.php.net/manual/en/class.iterator.php">Iterator</a> Interface.</p><p>The difference between them is that the IteratorAggregate is an interface that provides a way to retrieve an external iterator, while the Iterator is an interface that provides a standard way to traverse the elements of a data structure and retrieve their values and keys.</p><h3>What is an iterator from a general perspective?</h3><p>An iterator can be both an <strong>object</strong> and a <strong>design pattern</strong>. In this article, we are focusing on the iterator as an object but it is important to be aware of the Iterator design pattern because the are somehow related.</p><p>Here are some definitions:</p><blockquote>“<strong>An iterator is a data structure that iterates over a collection of elements to provide them, on demand, one after the other</strong>” (source : <a href="https://books.google.ro/books?id=I-tiDwAAQBAJ&amp;dq=%22An+iterator+is+a+data+structure+that+iterates+over+a+collection+of+elements+to+provide+them+on+demand+one+after+the+other%22&amp;pg=PA94&amp;source=ttb&amp;redir_esc=y#v=onepage&amp;q=%22An%20iterator%20is%20a%20data%20structure%20that%20iterates%20over%20a%20collection%20of%20elements%20to%20provide%20them%20on%20demand%20one%20after%20the%20other%22&amp;f=false">here</a> )</blockquote><blockquote>“<strong>An iterator is an object that allows iteration over some collection of values and maintains whatever state is necessary to keep track of the current “position” in the collection</strong>” (source : <a href="https://books.google.ro/books?id=4RChxt67lvwC&amp;dq=%22An+iterator+is+an+object+that+allows+iteration+over+some+collection+of+values+and+maintains+whatever+state+is+necessary+to+keep+track+of+the+current+position+in+the+collection%22&amp;pg=PA274&amp;source=ttb&amp;redir_esc=y#v=onepage&amp;q=%22An%20iterator%20is%20an%20object%20that%20allows%20iteration%20over%20some%20collection%20of%20values%20and%20maintains%20whatever%20state%20is%20necessary%20to%20keep%20track%20of%20the%20current%20position%20in%20the%20collection%22&amp;f=false">here</a> )</blockquote><blockquote>“<strong>An iterator is a simple kind of producer coroutine that yields a sequence of elements to a consumer coroutine. </strong>The iterator and the consumer can be viewed as separate computational processes” (source : <a href="https://books.google.ro/books?id=xpT6AQAAQBAJ&amp;dq=%22An+iterator+is+a+simple+kind+of+producer+coroutine+that+yields+a+sequence+of+elements+to+a+consumer+coroutine%22&amp;pg=PA506&amp;source=ttb&amp;redir_esc=y#v=onepage&amp;q=%22An%20iterator%20is%20a%20simple%20kind%20of%20producer%20coroutine%20that%20yields%20a%20sequence%20of%20elements%20to%20a%20consumer%20coroutine%22&amp;f=false">here</a> )</blockquote><p>If I would give a simple definition I would say that an <em>iterator is an object that allows us to parse the elements of a collection one after one</em>. The iterator is not the collection.</p><h3>Iterator implementation</h3><p>To implement an iterator we have to implement <a href="https://www.php.net/manual/en/class.iterator.php">the Iterator</a> interface by our class. The code presented on the official page could be run <a href="https://3v4l.org/BVJvR#v8.0.27">here</a>. The explanation for each method is pretty clear:</p><ul><li><a href="https://www.php.net/manual/en/iterator.rewind.php">Iterator::rewind</a> — Rewind the Iterator to the first element</li><li><a href="https://www.php.net/manual/en/iterator.valid.php">Iterator::valid</a> — Checks if current position is valid</li><li><a href="https://www.php.net/manual/en/iterator.current.php">Iterator::current</a> — Return the current element</li><li><a href="https://www.php.net/manual/en/iterator.key.php">Iterator::key</a> — Return the key of the current element</li><li><a href="https://www.php.net/manual/en/iterator.next.php">Iterator::next</a> — Move forward to next element</li></ul><h3>IteratorAggregate implementation</h3><p>As I said above we use IteratorAggregate to retrieve an already existing iterator. This is very useful in some situations as we may see in the following sections. A class that implements IteratorAggregate must implement the getIterator function.</p><ul><li><a href="https://www.php.net/manual/en/iteratoraggregate.getiterator.php">IteratorAggregate::getIterator</a> — Retrieve an external iterator</li></ul><p>Code from <a href="https://www.php.net/manual/en/class.iteratoraggregate.php">documentation</a> can be run <a href="https://3v4l.org/tYZkf#v8.0.27">here</a>.</p><h3>Useful use cases of iterator</h3><h3>1. Encapsulation</h3><p>In our days when we are struggling to write code that does not become legacy in the next sprint and pull a request that would not be rejected after code review so is important to follow standards. Of course, each organization has its own adopted standards but still, most of them are considering OOP as a must-have. Encapsulation as you may see <a href="https://medium.com/@alin.pintilie/the-4-pillars-of-oop-with-code-samples-in-php-da1b87b5ad46"><strong>here</strong></a> stands for hiding behavior (implementation) and proprieties.</p><p><strong>Hiding implementation</strong></p><p>When we are working with arrays for example keys and values are exposed. Also if you are iterating over it, to do something with its value you probably will expose some implementation. This case is treated <a href="https://medium.com/@alin.pintilie/how-to-encapsulate-behavior-using-an-iterator-to-meet-srp-99b24808ec5"><strong>here</strong></a><strong> </strong>and you can see the results below:</p><pre>public function storeInvoices(Vendor $vendor, string $dateFrom, string $dateTo)<br>{<br>    $invoiceIterator = new InvoiceIterator($vendor, $dateFrom, $dateTo);<br>    foreach ($invoiceIterator as $invoice) {<br>        $this-&gt;store($invoice);<br>    }<br>}</pre><p>We encapsulated the entire implementation and we can focus only on the current function purpose.</p><p><strong>Change implementation</strong></p><p>Another case could we when we have a collection built on top of an array but we want to change the implementation of that collection and maybe even the data structure that is built on.</p><p>We have the following case:</p><pre>$invoiceCollection = new InvoiceCollection();<br><br>foreach ($invoiceCollection as $invoice) {<br>    doSomethingWithInvoice($invoice)<br>}</pre><p>We suppose that this is a very used snippet in our project. As we saw that there are some memory limit issues, we need to find a way to improve memory usage. The problem is that this piece of code is very often used in our project, therefore we can not afford to change each implementation.</p><p>As we can see <a href="https://medium.com/@rtheunissen/efficient-data-structures-for-php-7-9dda7af674cd">here</a> could be many other data structure alternatives to an array. Also if we want to have a custom implementation (like a custom object storage) we should be able to change the implementation of InvoiceCollection without affecting the pieces of code that use this collection. We can see <a href="https://medium.com/@alin.pintilie/build-custom-php-object-storage-for-46-memory-saving-2afb57c1b228"><strong>here</strong></a><strong> </strong>the proposed solution. We can even find another way to improve performance and change the only implementation of InvoiceCollection using an iterator.</p><p>However it works like an adapter pattern, the iterator is an adaptor that allows you to interact with different data structures with the same interface.</p><h3>2. Improving memory usage with lazy loading</h3><p>We already saw one way of optimization but the main purpose of that example was to show how we can use the iterator to hide the implementation. Now, let’s focus on probably the most popular way of improving memory allocation using the iterator. This is the case with <strong>the lazy loading </strong>approach.</p><p>As one of the above definitions says, an iterator is a way of providing elements of a collection <em>on demand. </em>This<em> </em>is the opposite of getting all elements (eager loading).</p><p>A lazy loading approach could be used when retrieving data from a database or importing from a file as you can see <a href="https://medium.com/@alin.pintilie/lazy-loading-using-the-iterator-in-php-for-saving-90-of-memory-d421cb84f0b5"><strong>here</strong></a>. We can see in that article that results in terms of a memory consumption economy are significant (could reach 90%) and worth taking into consideration when designing a solution to a problem.</p><p>Of course, many other use cases are suitable like iterating over a directory structure or fetching data from an API but the most important aspect is understanding the mechanism behind it and choosing according to the needs.</p><h3>3. Custom collection</h3><p>If you are working with Laravel or other frameworks you are already familiar with PHP collections and the advantages of using them. However, if you want to understand how it is built under the hood or how to build your collection to suit your needs it is important to know something about the <a href="https://www.php.net/manual/en/class.iterator.php">Iterator</a> and <a href="https://www.php.net/manual/en/class.iteratoraggregate.php">IteratorAggregate</a>. <a href="https://medium.com/@alin.pintilie/how-to-build-your-own-php-collection-using-the-iterator-36737ab1fe06"><strong>Here</strong></a><strong> </strong>we have a very simple example of building our own collection.</p><h3><strong>Built in Iterators</strong></h3><p>As we now understand how iterators are working and how to build our iterator is important to not reinvent the wheel. Php already has a lot of ready-to-use iterators provided by Standard Php Library (<a href="https://www.php.net/manual/en/spl.iterators.php">SPL</a>) and could be suitable for us, depending on the demands.</p><p>If this article was useful for you stay in touch for more to come.</p><p>Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72f05d6940c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy loading using the iterator in PHP for saving 90% of memory]]></title>
            <link>https://medium.com/@alin.pintilie/lazy-loading-using-the-iterator-in-php-for-saving-90-of-memory-d421cb84f0b5?source=rss-a55d872292e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d421cb84f0b5</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[iterator-pattern]]></category>
            <category><![CDATA[iterators]]></category>
            <dc:creator><![CDATA[Alin Pintilie]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 07:41:03 GMT</pubDate>
            <atom:updated>2023-02-06T08:03:01.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dR2TWrg42whNtQd1zCfBQQ.jpeg" /></figure><p>Of course, there are some advantages when it comes to eager loading (loading all data one at a time) like processing speed or code complexity but there are cases when memory is more important than speed.</p><p>Please see below two popular examples of eager loading :</p><pre>public function getAllInvoices()<br>{<br>    $statement = Db::getInstance()-&gt;prepare(&quot;select * from Invoices&quot;);<br>    $statement-&gt;execute();<br>    return $statement-&gt;fetchAll(PDO::FETCH_OBJ);<br>}<br><br>public function importFromFile($filePath)<br>{<br>    $fileContent = file_get_contents($filePath);<br>    $explodedContent = explode(&quot;\n&quot;, $fileContent);<br>    $arrayOfElements = array_map(&#39;json_decode&#39;, $explodedContent);<br><br>    retrun arrayOfElements;<br>}<br><br>$documentStoringService = new DocumentStoringService();<br><br>//case 1<br>foreach (getAllInvoices() as $invoice) {<br>  $documentStoringService-&gt;store($invoice);<br>}<br><br>//case 2<br>foreach (importFromFile() as $invoice) {<br>  $documentStoringService-&gt;store($invoice);<br>}</pre><p>We have two common cases when we fetch some data and then we parse them one by one. This code has nothing special except the fact that those two functions could return a big number of elements which could require an enormous amount of memory.</p><p>The question is why do we need to load all data in memory when we could load one at a time? Fortunately, there is a mechanism for loading one at a time and as you already guessed, it is the iterator. Retrieving items from database</p><p>There are many ways of getting items from the database depending on the data access layer used. In our example, we are using PDO (PHP Data Objects) extension. Of course, PDO already has a <a href="https://phpdelusions.net/pdo/fetch_modes#FETCH_LAZY">ready-to-use lazy mechanism</a> that is worth taking into consideration when you want to deal with lazy loading. However, we are building our solution on top of <a href="https://medium.com/@alin.pintilie/php-iterator-72f05d6940c8">iterator</a> because of <strong>other advantages</strong> that may bring.</p><p>Below is the implementation of the Iterator interface:</p><pre>class LazyDatabaseInvoiceIterator implements Iterator<br>{<br>    private mixed $row;<br>    private int $index = 0;<br>    private mixed $statement;<br><br>    public function current(): mixed<br>    {<br>        return $this-&gt;row;<br>    }<br><br>    public function next(): void<br>    {<br>        $this-&gt;row = $this-&gt;statement-&gt;fetch(PDO::FETCH_OBJ);<br>        $this-&gt;index++;<br>    }<br><br>    public function key(): int<br>    {<br>        return $this-&gt;index;<br>    }<br><br>    public function valid(): bool<br>    {<br>        return !empty($this-&gt;row);<br>    }<br><br>    public function rewind(): void<br>    {<br>        $this-&gt;statement = Db::getInstance()-&gt;prepare(&quot;select * from Invoices &quot;);<br>        $this-&gt;statement-&gt;execute();<br>        $this-&gt;row = $this-&gt;statement-&gt;fetch(PDO::FETCH_OBJ);<br>    }<br>}</pre><p>For our purpose, we need to fetch all invoices from the database as you can see in <em>the rewind</em> function. Using the PDO <em>fetch</em> (instead of <em>fetchAll</em> as it is inside <em>the getAllInvoices</em>) function we will get only one row at a time which is assigned to <em>$this-&gt;row</em> attribute. After checking if the row is valid we get the current fetched object. Inside <em>the next</em> function, we call again <em>$this-&gt;statement-&gt;fetch(PDO::FETCH_OBJ) </em>but because of internal pointer implementation, PDO will return the next element from the database. In this way, our iterator can provide fetched elements one after one without keeping all elements in memory.</p><p>The above implementation could be simplified by implementing <a href="https://www.php.net/manual/en/class.iteratoraggregate.php">IteratorAggregate</a></p><p>Using LazyDatabaseInvoiceIterator in foreach:</p><pre>$invoices = new LazyDatabaseInvoiceIterator();<br>foreach ($invoices as $invoice) {<br>  $documentStoringService-&gt;store($invoice);<br>}</pre><p><strong>What is the economy in terms of memory usage?</strong></p><p>I run the script in <strong>PHP 8 </strong>with <strong>20.908 elements</strong> (Invoice objects in the database). The memory usage with eager loading was 10,57 Mb. After the implementation of LazyDatabaseInvoiceIterator, the usage was 0,82 Mb. We managed to save 9,75 MB (<strong>92,24%</strong>).</p><h3>Reading items from a file</h3><p>When it comes to reading items from a file of course there are many ways. To put it, in contrast, I used as a bad practice <a href="https://www.php.net/manual/en/function.file-get-contents.php">file_get_contents()</a>. This is not a bad function itself but could be a better way of reading from files especially when the file content is very large. However, because file_get_contents uses memory mapping could be used inside the iterator too. It all depends on your requirements. However, in our case, we will use an iterator.</p><pre>class LazyFileInvoiceIterator implements Iterator<br>{<br>    private int $pointer = 0;<br>    private string $line;<br>    private SplFileObject $file;<br>    <br>    public function __construct(string $filePath)<br>    {<br>        $this-&gt;file = new SplFileObject($filePath);<br>    }<br><br>    public function current(): mixed<br>    {<br>        return json_decode($this-&gt;line);<br>    }<br><br>    public function next(): void<br>    {<br>        $this-&gt;line = $this-&gt;file-&gt;fgets();<br>        $this-&gt;pointer++;<br>    }<br><br>    public function key(): int<br>    {<br>        return $this-&gt;pointer;<br>    }<br><br>    public function valid(): bool<br>    {<br>        return !empty($this-&gt;line)  &amp;&amp; $this-&gt;file-&gt;valid();<br>    }<br><br>    public function rewind(): void<br>    {<br>        $this-&gt;pointer = 0;<br>        $this-&gt;file-&gt;seek(0);<br>        $this-&gt;line = $this-&gt;file-&gt;fgets();<br>    }<br>}</pre><p>I used <a href="https://www.php.net/manual/en/class.splfileobject.php">SplFileObject</a> for a more elegant approach. In <em>the rewind</em> function, I set the pointer to 0, set start reading from line 0, and get the first line content. Maybe you are wondering why I use <em>json_decode</em> in <em>the current </em>function. It is because I read from a <a href="https://github.com/ndjson/ndjson-spec">.ndjson</a> file which is very useful for storing objects and also make decoding very easy as you can see.</p><p>Using LazyFileInvoiceIterator in foreach:</p><pre>$fileIterator = new LazyFileInvoiceIterator($filePath);<br>foreach ($fileIterator as $invoice){<br>    $documentStoringService-&gt;store($invoice);<br>}</pre><p><strong>What is the economy in terms of memory usage?</strong></p><p>I run the script in <strong>PHP 8 </strong>with <strong>100.000 elements</strong> (Invoice objects in the database). The memory usage with eager loading was <strong>67.17</strong> Mb. After the implementation of LazyDatabaseInvoiceIterator, the usage was <strong>0,02</strong> Mb. In this case, the difference is huge.</p><p>However, could be some downsides like speed or more intense processing but in some cases, memory saving is more important. Feel free to adapt it to your own uses.</p><p>Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d421cb84f0b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to encapsulate behavior using PHP iterator to comply SRP]]></title>
            <link>https://medium.com/@alin.pintilie/how-to-encapsulate-behavior-using-an-iterator-to-meet-srp-99b24808ec5?source=rss-a55d872292e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/99b24808ec5</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[single-responsibility]]></category>
            <category><![CDATA[encapsulation]]></category>
            <category><![CDATA[iterators]]></category>
            <dc:creator><![CDATA[Alin Pintilie]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 07:30:10 GMT</pubDate>
            <atom:updated>2023-02-06T14:39:14.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5j6b-KvszlJD-ylTLcyqg.jpeg" /></figure><p>OOP is still alive and some of us are still trying to encapsulate (more details <a href="https://medium.com/@alin.pintilie/the-4-pillars-of-oop-with-code-samples-in-php-da1b87b5ad46">here</a>) proprieties and behavior. During my work on a legacy project surfing on pure PHP with no framework, and no built-in data collection (except the arrays), I often tried to follow the OOP standards, including encapsulation. Most of the time I managed to use it when I had to build a new class for a certain model. However, we can also encapsulate behavior when it comes to building a service class.</p><p>For the purpose of this article, we can think about the following scenario: W<em>e are working on a legacy project where refactoring </em>possibilities<em> are very restricted. In a service class, we have to fetch some data (an array of objects) from an API, then we need to filter based on some conditions, then we need to clear some data, save some logs and process elements in the foreach loop. </em>It does not seem to be a hard task except for the fact that we also need to meet the criteria for SRP (<a href="https://www.freecodecamp.org/news/solid-principles-single-responsibility-principle-explained/">Single Responsibility Principle</a>).</p><p><strong>Initial code</strong></p><pre>public function storeInvoices(Vendor $vendor, string $dateFrom, string $dateTo)<br>{<br>    $loggerService =  new LoggerService();<br>    $invoiceService = new InvoiceService();<br><br>    $invoices = $invoiceService-&gt;fetchInvoices($vendor, $dateFrom, $dateTo);<br>    $loggerService-&gt;log(&quot;Fetched invoices: &quot; . json_encode($invoices));<br><br>    foreach ($invoices as $invoice) {<br>        if ($invoiceService-&gt;isDue($invoice)) {<br>            $this-&gt;store($invoice);<br>        }<br>    }<br>}</pre><p>As you can see, we broke the SRP rule because we have more than one action related to its purpose. This function should do one thing: store invoices. Instead, it fetches invoices, logs something and filters based on some condition and calls the store function.<br>Now let`s do some refactoring to meet our purpose. First of all, we need to establish which parts should not stand inside this function. There are three extra parts: fetching, logging and filtering. So our function should receive in a way, already fetched and filtered invoices. We can not change the parameter list because we are working in a legacy code but we can reach that by using an Iterator (more about iterators <a href="https://medium.com/@alin.pintilie/php-iterator-72f05d6940c8"><strong>here</strong></a>).</p><p><strong>New code</strong></p><pre>public function storeInvoices(Vendor $vendor, string $dateFrom, string $dateTo)<br>{<br>    $invoiceIterator = new InvoiceIterator($vendor, $dateFrom, $dateTo);<br>    foreach ($invoiceIterator as $invoice) {<br>        $this-&gt;store($invoice);<br>    }<br>}</pre><p>Now, our function looks much better and it is doing one thing. Maybe you are wondering what is happening behind scenes. Let’s take a look:</p><p><strong>Iterator implementation</strong></p><pre>class InvoiceIterator implements Iterator<br>{<br>    private $invoiceService = null;<br>    private $invoices = [];<br>    private $index = 0;<br>    private $vendor;<br>    private $loggerService;<br>    private $dateFrom;<br>    private $dateTo;<br><br>    public function __construct(Vendor $vendor, string $dateFrom, string $dateTo)<br>    {<br>        $this-&gt;loggerService = new LoggerService();<br>        $this-&gt;invoiceService = new InvoiceService();<br>        $this-&gt;vendor = $vendor;<br>        $this-&gt;dateFrom = $dateFrom;<br>        $this-&gt;dateTo = $dateTo;<br>    }<br><br>    public function current(): mixed<br>    {<br>        return $this-&gt;invoices[$this-&gt;index];<br>    }<br><br>    public function next(): void<br>    {<br>        $this-&gt;index++;<br>    }<br><br>    public function key(): mixed<br>    {<br>        return $this-&gt;index;<br>    }<br><br>    public function valid(): bool<br>    {<br>        return !empty($this-&gt;invoices[$this-&gt;key()]) &amp;&amp; $this-&gt;invoiceService-&gt;isDue($this-&gt;current());<br>    }<br><br>    public function rewind(): void<br>    {<br>        $this-&gt;invoices = $this-&gt;invoiceService-&gt;fetchInvoices($this-&gt;vendor, $this-&gt;dateFrom, $this-&gt;dateTo);<br>        $this-&gt;loggerService-&gt;log(&quot;Fetched invoices: &quot; . json_encode($this-&gt;invoices));<br>    }<br>}</pre><p>Inside the <em>constructor</em>, we are instantiating and setting some variables. <em>The rewind</em> function is dealing with fetching and logging. Also, logging could be encapsulated inside the fetchInvoices function. The others function are just standard for iterating over an array. <em>The key</em> function returns the current key, <em>next</em> increments the index and current returns the current item(invoice).</p><p>Of course, you could see some improvements in our code but our main purpose was to delegate some responsibilities to an iterator object in order to reach SRP.</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99b24808ec5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build your own PHP collection using the iterator]]></title>
            <link>https://medium.com/@alin.pintilie/how-to-build-your-own-php-collection-using-the-iterator-36737ab1fe06?source=rss-a55d872292e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/36737ab1fe06</guid>
            <category><![CDATA[php-collection]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[iterators]]></category>
            <dc:creator><![CDATA[Alin Pintilie]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 07:18:49 GMT</pubDate>
            <atom:updated>2023-02-06T08:04:22.265Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGhwSeY0wttXcz0NO8jTOQ.jpeg" /></figure><p>If you are a PHP programmer you understand what array means for us. We gravitate around it. Indubitably there are a lot of advantages but also there are some drawbacks. For example, in java, if you want to work with a collection, you can define what kind of data you want to store and you should not worry later if that collection could contain other data too. From this perspective, we can not do this in PHP, so in order to achieve this we may use a collection. A collection could be just a wrapper over an array. If you are familiar with <a href="https://laravel.com/docs/9.x/collections">Laravel</a> or another PHP framework maybe you know what I mean.</p><p>For the purpose of showing how to build a collection, I propose the following scenario. We are working with Invoices objects and we want to have a collection that contains only objects of Invoice type. Of course, we can use an array and add validation every time when we add and retrieve items but this could be inefficient and error-prone. So we are building our own collection that will be framework agnostic.</p><p>In order to do this we use <a href="https://www.php.net/manual/en/class.iteratoraggregate.php">IteratorAggregate</a>. More about it can be read <a href="https://medium.com/@alin.pintilie/php-iterator-72f05d6940c8"><strong>here</strong></a>.</p><pre>class InvoiceCollection implements IteratorAggregate {<br>    private $invoices = array();<br><br>    public function add(Invoice $invoice)<br>    {<br>        $this-&gt;invoices[] = $invoice;<br>    }<br><br>    public function getIterator(): Traversable<br>    {<br>        return new ArrayIterator($this-&gt;invoices);<br>    }<br>}</pre><p>Using the IteratorAggregate we must implement <em>the getIterator </em>function. All that is done is to return a Traversable. Basically “we convert” $invoices array into an Iterator with <a href="https://www.php.net/manual/en/class.arrayiterator.php">ArrayIterator</a> function. Also, we implement <em>add </em>function that will be the unique entry point of items into the array. Because we declared the parameter type as Invoice this function will accept an only objects of that type.</p><p>Using this collection is very easy:</p><pre>//adding an item <br>$invoiceCollection = new InvoiceCollection();<br>$invoiceCollection-&gt;add(new Invoice(1));<br><br>//iterating over it<br>foreach ($invoiceCollection as $invoice) {<br>        //do something with invoice<br>}</pre><p>Now we should not implement any other logic when adding or iterating over this collection as it contains only Invoice objects. Of course, we can add more functionality like get, delete, count, etc. functions to our class. Depending on your own needs feel free to use the power of this mechanism.</p><p>Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36737ab1fe06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build custom php object storage for 46% memory saving]]></title>
            <link>https://medium.com/@alin.pintilie/build-custom-php-object-storage-for-46-memory-saving-2afb57c1b228?source=rss-a55d872292e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2afb57c1b228</guid>
            <category><![CDATA[iterators]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[memory-improvement]]></category>
            <category><![CDATA[object-storage]]></category>
            <dc:creator><![CDATA[Alin Pintilie]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 07:10:54 GMT</pubDate>
            <atom:updated>2023-02-06T08:04:58.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3BcOAhgk9mmNzHtw215zQ.jpeg" /></figure><p>As we know the <strong>iterator</strong> is a versatile and powerful tool that can be used in different scenarios (a few examples <a href="https://medium.com/@alin.pintilie/php-iterator-72f05d6940c8"><strong>here</strong></a>). One use case is building a custom collection (example here). Building our collection could have some advantages <em>like restricting stored elements to have unique data types</em> in that collection but when it comes to memory usage we do not have an advantage. However, we can find a workaround for this particular case.</p><p>Initial iterator</p><pre>class InvoiceCollection implements IteratorAggregate{<br>    private array $invoices;<br><br>    public function __construct()<br>    {<br>        $this-&gt;invoices = array();<br>    }<br><br>    public function add(Invoice $invoice)<br>    {<br>        $this-&gt;invoices[] = $invoice;<br>    }<br><br>    public function getIterator(): Traversable<br>    {<br>        return new ArrayIterator($this-&gt;invoices);<br>    }<br>}<br><br>//adding to collection<br>$invoiceCollection = new InvoiceCollection();<br>foreach ($invoices as $invoice) {<br>  $invoiceCollection-&gt;add($invoice);<br>  $index++;<br>}<br><br>//consuming collection<br>foreach ($invoiceCollection as $invoice) {<br>    doSomethingWithInvoice($invoice)<br>}</pre><p>As you can see this collection is built on top of the array. To improve memory usage we could find a few solutions. We can use <a href="https://medium.com/@rtheunissen/efficient-data-structures-for-php-7-9dda7af674cd">different data structure</a>s but depending on the PHP version, this solution could not bring any major improvement. Instead of this, we could build our custom object storage using the iterator interface.</p><p>Let’s start with the idea that storing an object inside an array takes more memory than storing a string (not the purpose of this article to explain that). So if we find a way to transform an object into a string we could start to think of a solution. This is very simple, we can just use <a href="https://www.php.net/manual/en/function.serialize.php">serialize()</a> function. Also if we would have a mechanism to reverse the process of serialization we have half of the solution. In fact, we have a function for this case too: <a href="https://www.php.net/manual/en/function.unserialize.php">unserialize()</a></p><p>The other part would be to call <a href="https://www.php.net/manual/en/function.serialize.php"><em>serialize</em></a><em> </em>function every time we add an element in the array (so we store a string representation of an object) and then call <a href="https://www.php.net/manual/en/function.unserialize.php"><em>unserialize</em></a> function whenever we take an element out of the array (so we transform the string in object again).</p><p>Of course, we will solve this mystery with the help of an iterator :)</p><pre>class ObjectStorage implements Iterator{<br>    private array $objects = array();<br>    private int $index = 0;<br><br>    public function add(object $object)<br>    {<br>        $serializedObject = serialize($object);<br>        $this-&gt;objects[] = $serializedObject;<br>    }<br><br>    public function current(): mixed<br>    {<br>        return unserialize($this-&gt;objects[$this-&gt;key()]);<br>    }<br><br>    public function next(): void<br>    {<br>        $this-&gt;index++;<br>    }<br><br>    public function key(): mixed<br>    {<br>        return $this-&gt;index;<br>    }<br><br>    public function valid(): bool<br>    {<br>        return !empty($this-&gt;objects[$this-&gt;key()]);<br>    }<br><br>    public function rewind(): void<br>    {<br>         $this-&gt;index = 0;<br>    }<br>}</pre><p>Now we have the magic ObjectStorage, it is time to change the implementation of our InvoiceCollection.</p><pre>class InvoiceCollection implements IteratorAggregate{<br>    private ObjectStorage $invoices;<br><br>    public function __construct()<br>    {<br>        $this-&gt;invoices = new ObjectStorage();<br>    }<br><br>    public function add(object $invoice)<br>    {<br>        $this-&gt;invoices-&gt;add($invoice);<br>    }<br><br>    public function getIterator(): Traversable<br>    {<br>        return $this-&gt;invoices;<br>    }<br>}</pre><p>We changed the type of $invoices attribute to ObjectStorage type and also the return type of the getIterator function. As ObjectStorage implements the iterator, ObjectStorage is a type of Traversable. Also, we changed the implementation of add function to suit the actual interface for ObjectStorage.</p><p><strong>What is the economy in terms of memory usage?</strong></p><p>I run the script in <strong>PHP 8 </strong>with <strong>100.000 elements</strong> (Invoice objects). The memory usage in the first case when plain objects were stored was 52,85 Mb. After the implementation of ObjectStorage, the usage was 28,44 Mb. We managed to save 24,41 MB (<strong>46%</strong>).</p><p>This is not perfect solution for all cases but there are situations when the memory limit could be touched if no optimization is done. For example, running a script on a large dataset. Feel free to adapt to your own situation.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2afb57c1b228" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate token usage with variables and scripts in Postman]]></title>
            <link>https://medium.com/@alin.pintilie/automate-token-usage-with-variables-and-scripts-in-postman-ab6bcdf71777?source=rss-a55d872292e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab6bcdf71777</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Alin Pintilie]]></dc:creator>
            <pubDate>Sat, 18 Jun 2022 16:12:05 GMT</pubDate>
            <atom:updated>2022-06-18T16:16:42.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8EbJvehzO81wapZMDH_cA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@christinhumephoto?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Christin Hume</a> on <a href="https://unsplash.com/s/photos/technology?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Did you know that you don’t need anymore to copy the access token returned from the login method into the header of the others requests. Also if you work on test environment you don’t have to change all urls for all other requests in order to switch to production. Postman provides easy to use variable and scripts that help you to save time. We are going to discuss two examples where variables and scripts can be used:</p><ul><li>First of all lets <strong>create a collection</strong> named SmartCollection (New -&gt; Collection-&gt;Create</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*gLTV47iqHalPZkiUpMOgkw.png" /><figcaption>Adding a new collection</figcaption></figure><ul><li>Than we need to edit <strong>collection </strong>(Go to SmartCollection -&gt; Click on … (three dots button) -&gt; Edit )</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*9wSKbtHz8yNh4XZj7AL1dw.png" /></figure><h3><strong>Variables</strong></h3><ul><li>now we are going to Variables tab and <strong>create two variables : </strong><em>Url </em>and <em>Token. </em>For the testing purpose we can set “localhost” (you can put your testing url) to <em>url inital and current value</em> and click “Update”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*xcM4vWk6fNuVDtem_-GOew.png" /></figure><ul><li>Now we can add a new request by going to SmartCollection , click on three dots (…) -&gt;Add request. In the url section we set our route using Url variable followed by our route. For this we need to <strong>type variable name between double curly brackets </strong>(e.g. <em>{{my_var_name}}</em> )</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sE17MbF3JQm9qeHwudR74Q.png" /></figure><p>If you click send we can test if it is working.</p><h3>Scripts</h3><p>In order to fulfill our purpose we need to automate token assignation so we can make requests without being need to copy it in header every time. If we need access token being present in the Header we suppose that we have an authorization endpoint witch will return the access token so we need to copy and paste it in the header. Now let do it in the smart way</p><ul><li>let`s create a new request for authorization endpoint using the same way as described above (e.g. /auth)</li><li>go to Tests tab and paste the following script:</li></ul><pre>var jsonData <strong>=</strong> JSON.<strong>parse</strong>(responseBody);</pre><pre>pm.collectionVariables.<strong>set</strong>(&quot;Token&quot;, jsonData.data.token);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCZel9yDNj0Yqnfw9ka1qA.png" /></figure><ul><li>in second line replace the section <em>“jsonData.</em><strong><em>data.token</em></strong><em>” </em>with your tag according to your response structure. Please see my response :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*paMn7Fc6MfCPAw23R6FCGg.png" /></figure><ul><li>now you can call /auth endpoint to test our script. You should be able to see actual Token variable value by going to SmartCollection -&gt; Click on … (three dots button) -&gt; Edit -&gt; Variables Tab</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*zKSf78Ieq2jXySbUPehGPA.png" /></figure><ul><li>finally we can use token in all methods by setting this variable in Header. Go to the first endpoint than to Headers tab and add Token parameter. Please note then if you are using anther authentication standard (e.g. OAuth) you can pass Token variable in same way: <em>{{Token}}</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*Fvj85722q0Cx17UJzAc9Xw.png" /></figure><h3><strong>Conclusion</strong></h3><p>Now you should be able to automate your authentication process in Postman using variable and scripts.</p><p>Thank you</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab6bcdf71777" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract class vs interface]]></title>
            <link>https://medium.com/@alin.pintilie/if-you-plan-to-have-an-interview-for-a-development-position-it-is-a-high-probability-to-face-the-cf293ed06e4f?source=rss-a55d872292e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf293ed06e4f</guid>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[abstract-class]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Alin Pintilie]]></dc:creator>
            <pubDate>Sat, 22 Jan 2022 17:17:26 GMT</pubDate>
            <atom:updated>2022-06-06T05:13:12.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tgi_i7u0hUht2hz6g2_T5A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@noahhalford20?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Noah Halford</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you plan to have an interview for a development position it is a high probability to face the following question: “What is the difference between an abstract class and an interface?”. This was an inconvenient question for me as well but I have got some clearance after I read the book “The object oriented thought process” (Matt Weisfeld). In this article I am trying to sintetize the main aspects regarding these two concepts.</p><p>Before diving into the explanation of the differences we need to understand that both abstract class and interface are called contracts. A contract is a formal agreement between two parties. In the development process a contract is involved when we firstly want to define some prerequisites for a class or for a type of classes. All the classes that will comply with this contract must follow the rules defined by it by implementing unimplemented methods.</p><h3>Abstract class</h3><p>An abstract class <strong>is defined by using keyword abstract and must contain at least one abstract method</strong> (that does not have any implementation). This means an abstract class could also provide concrete methods. Considering these, a child class that extends an abstract class must implement only those methods declared abstract into the parent class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b7b9d3902e88deab3b76472951dcafc/href">https://medium.com/media/2b7b9d3902e88deab3b76472951dcafc/href</a></iframe><h3>Interface</h3><p>First of all it is important to say that when we talk about the interface we are thinking of a class defined as an interface . There is another concept called interface which describes the public methods and attributes of a class but it is not the subject of this article (see <a href="https://medium.com/@alin.pintilie/the-4-pillars-of-oop-with-code-samples-in-php-da1b87b5ad46">encapsulation</a>). A class defined as an <strong>interface does not provide any implementation but a class that implements an interface must provide implementation for all its methods</strong> except abstract classes that implement that interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8de27f7a3ee02b9f2fed3619582b3e8b/href">https://medium.com/media/8de27f7a3ee02b9f2fed3619582b3e8b/href</a></iframe><h3>Difference between them:</h3><ul><li>a child class can inherit only from a parent class but implement many interfaces</li><li>for inheritance is used extend keyword and for implementations is used implement keyword</li><li>an abstract class can provide implementation whereas an interface provide only abstract methods</li><li>an abstract class should be used for classes that are related in some way while an interface should be used for specifying the same behavior across classes that have no connection</li><li>an abstract class can have access modifiers but interface supposed to have only public methods</li><li>in some programing languages (like php), an abstract class can have properties while interface can have only methods</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf293ed06e4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>