<?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 Ujjwal Ojha on Medium]]></title>
        <description><![CDATA[Stories by Ujjwal Ojha on Medium]]></description>
        <link>https://medium.com/@ojhaujjwal?source=rss-7896e01eaa28------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ywncpw2Ef6U4k7SqtQR1mQ.jpeg</url>
            <title>Stories by Ujjwal Ojha on Medium</title>
            <link>https://medium.com/@ojhaujjwal?source=rss-7896e01eaa28------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 04:22:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ojhaujjwal/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[Decorators Composition in TypeScript]]></title>
            <link>https://medium.com/@ojhaujjwal/decorators-composition-in-typescript-86f5c132464f?source=rss-7896e01eaa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/86f5c132464f</guid>
            <dc:creator><![CDATA[Ujjwal Ojha]]></dc:creator>
            <pubDate>Thu, 11 Jun 2020 16:12:42 GMT</pubDate>
            <atom:updated>2020-06-11T16:12:42.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTj0zUb6TZmLlI-VQlR80A.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/01OHD0PWUh0">https://unsplash.com/photos/01OHD0PWUh0</a></figcaption></figure><p>Decorators are an experimental feature of TypeScript that can be attached to a <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators">class declaration</a>, <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators">method</a>, <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#accessor-decorators">accessor</a>, <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#property-decorators">property</a>, or <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#parameter-decorators">parameter</a> in the form @expression. Read more about decorators <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#decorators">here</a>.</p><p>Although decorators are an experimental feature, TypeScript based server-side frameworks such as the following heavily use this feature:</p><ol><li><a href="https://docs.nestjs.com/">NestJS</a></li><li><a href="https://loopback.io/doc/en/lb4/">Loopback</a></li></ol><p>If you have used NestJS, you may have seen decorators in controllers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6b79285a2997ed32ebada65af1ffb58/href">https://medium.com/media/f6b79285a2997ed32ebada65af1ffb58/href</a></iframe><p>You can do a lot of things in decorators. One of the things that is very useful is to add <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#metadata">metadata</a> to the decorator target using <a href="https://rbuckton.github.io/reflect-metadata/">Reflection API</a>.</p><p>Frameworks like NestJs expose plenty of framework APIs as decorators which attaches metadata to decorator target and after that Reflection API is used to access the attached metadata.</p><p>For example, the `<a href="https://medium.com/@AuthenticationG">@Controller</a>()` decorator in a class will register the class in the metadata as a controller for the specified HTTP route. The metadata will be read by the framework to know which controller is responsible for which route.</p><p>Most of the times, I find myself using the same set of decorators together like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a902d4c9c43ed4c25c29e982badcbf33/href">https://medium.com/media/a902d4c9c43ed4c25c29e982badcbf33/href</a></iframe><p>It may be fine if you have just a few controllers, but it gets hard to maintain if you have lots of controllers.</p><p>A neat way to organize a group of decorators that come together in your application is to expose a new decorator that composes the group of decorators internally.</p><p>Imagine how neat it would be if we could so something like this for the above two controller classes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91f9308c75790d86f887f0d2554b7a1c/href">https://medium.com/media/91f9308c75790d86f887f0d2554b7a1c/href</a></iframe><p>Let’s try to implement the new decorator AdminController. In theory, pseudo-code for the decorator could be something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b941975193fd9692fa4e8f4e723f4b3b/href">https://medium.com/media/b941975193fd9692fa4e8f4e723f4b3b/href</a></iframe><p>Like with any decorator, it has to implement a certain type. I am specifically creating a class decorator in this post, but the idea of decorator composition should apply to other type of decorators as well. Here’s the actual implementation of the fictional AdminController decorator that we have used in the above gists.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10e79446a4d206f32853df961dd2ca79/href">https://medium.com/media/10e79446a4d206f32853df961dd2ca79/href</a></iframe><h4>Final Thoughts</h4><p>Decorators are currently in <a href="https://github.com/tc39/proposal-decorators">stage 2 proposal</a> for JavaScript, but they are already used heavily in the TypeScript community.</p><p>Please feel free to play around with decorator patterns like this and share tips and tricks with the awesome JavaScript community.</p><p>If you like the decorator composition pattern, you may also like <a href="https://github.com/ojhaujjwal/class-validator-js-joda/">this library</a> that I recently authored based on the pattern.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86f5c132464f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why and When to use Generator instead of Array in PHP]]></title>
            <link>https://medium.com/the-iconic-engineering/why-and-when-to-use-generator-instead-of-array-in-php-fe5c60231746?source=rss-7896e01eaa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe5c60231746</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[memory-improvement]]></category>
            <dc:creator><![CDATA[Ujjwal Ojha]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 23:50:56 GMT</pubDate>
            <atom:updated>2020-04-23T23:50:56.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why and when to use a generator instead of an array in PHP</h3><p>A <a href="https://en.wikipedia.org/wiki/Generator_(computer_programming)">generator</a> is a VERY powerful concept that provides a host of benefits. I believe they are very under-used and under-appreciated by PHP developers. In this post, I will explain what are the advantages of generators and some of the example usages that will hopefully motivate you to use more and more generators in PHP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSaGuNMxqIsz9S8zTS11RQ.jpeg" /></figure><h3>First Things First, What is an Iterator in PHP</h3><p>A generator is a special type of <a href="https://www.php.net/manual/en/class.iterator.php">Iterator</a> that provides an easy way to implement Iterators in PHP for a lot of use-cases. So, we need to understand what is an Iterator before we learn what is a generator.</p><p>Arrays are not the only thing over which you can iterate using foreach in PHP. Any instance of any class implementing <a href="https://www.php.net/manual/en/class.iterator.php">Iterator</a> interface can be iterated using foreach.</p><p>Here’s a simple example of a file iterator. It simply receives a file path as an argument and then you can iterate over the object using foreach.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c17bc445bff0e69026527795268c7d3c/href">https://medium.com/media/c17bc445bff0e69026527795268c7d3c/href</a></iframe><blockquote>Bonus Tip: You can also create iterators implementing <a href="https://www.php.net/manual/en/class.iteratoraggregate.php">IteratorAggregate interface</a>.</blockquote><h3>Why Iterator instead of Array</h3><p>Suppose there’s a function that expects a list of image contents to upload it to somewhere like AWS S3 bucket.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ef76f69b0d99b3634a8849bf87af352/href">https://medium.com/media/2ef76f69b0d99b3634a8849bf87af352/href</a></iframe><p>The problem with the above code is that you load all the images to memory even before you need any one of the images.</p><p>Instead, if you change the above code to support Iterator, the iterator may load images lazily during iteration, which avoids loading all the images to memory at once.</p><blockquote>Bonus Tip: Use iterable typehint to support arrays as well as Iterator.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e70c96133e19d9e73d26c3689840fa2/href">https://medium.com/media/8e70c96133e19d9e73d26c3689840fa2/href</a></iframe><h3>So what is a Generator?</h3><p>Generator is the easiest way to generate lazy loading iterators. Generators expose a yield keyword which allows an easy way to create lazy loading iterators. The first code example of an Iterator can be converted to a generator quite easily, requiring much less code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ae315f6006eb8a56b8562dd6f6f16e3/href">https://medium.com/media/8ae315f6006eb8a56b8562dd6f6f16e3/href</a></iframe><h3>Benchmarking</h3><p>Let’s do some profiling of the above code using a generator vs the following equivalent code using an array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70618aca311dd529fc71eaeeacf63433/href">https://medium.com/media/70618aca311dd529fc71eaeeacf63433/href</a></iframe><p>I used <a href="https://github.com/tideways/php-xhprof-extension">xhprof</a> extension for profiling the above two code snippets for printing contents of a 5MB file and here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TTK_xfWBG511Ri-xl3oRA.png" /></figure><p>The first one is the report of the above PHP script which uses an array and the second one is the report of the php script which uses a generator. We want to focus on the memory side of the profiling which is marked by the red box and the results are astounding. The script using generator beats the other script using an array by a huge margin.</p><h3>Some other benefits of Generators</h3><h4>Early Break</h4><p>With Generators, you may choose to simply break from the loop after you are done with the loop and you will save a lot of memory done by lazy loading data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8b8704b985bae6b3985832ff189264a/href">https://medium.com/media/b8b8704b985bae6b3985832ff189264a/href</a></iframe><h4>Send data to Generators</h4><p>You can use the send method of generator object which allows you to pass values <strong>back</strong> to the generator as a yield expression. This turns the one-way communication from the generator to the caller into a two-way channel between the two.</p><p>Here’s an example of using a logger utility using send() :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00365af493a5e505441b9debf6f433df/href">https://medium.com/media/00365af493a5e505441b9debf6f433df/href</a></iframe><h4>Co-routines</h4><p>The two-way communication between the caller and the generator using the send method can be used to implement cooperative multitasking.</p><p>Basically, it means switching between multiple tasks by running one task at a time and then switching it with another task.</p><p>Nikita Popov wrote an <a href="https://nikic.github.io/2012/12/22/Cooperative-multitasking-using-coroutines-in-PHP.html">excellent blog</a> on how to implement Cooperative multitasking using coroutines using PHP generators.</p><h3>Conclusion</h3><p>Generators are an under-used concept that provides so many benefits and I think it should be used more often wherever applicable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe5c60231746" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-iconic-engineering/why-and-when-to-use-generator-instead-of-array-in-php-fe5c60231746">Why and When to use Generator instead of Array in PHP</a> was originally published in <a href="https://medium.com/the-iconic-engineering">THE ICONIC Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing Development Environment in Mac: Performance Enhancement]]></title>
            <link>https://medium.com/devcupboard/dockerizing-development-environment-in-mac-performance-debugging-dac16aa4524?source=rss-7896e01eaa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/dac16aa4524</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ujjwal Ojha]]></dc:creator>
            <pubDate>Tue, 10 Jul 2018 08:30:18 GMT</pubDate>
            <atom:updated>2018-11-05T04:09:12.529Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5KaZGVkx12TeIMjpMlGHg.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/PaBnxI25KYk">https://unsplash.com/photos/PaBnxI25KYk</a></figcaption></figure><p>Recently, I moved from Ubuntu to Mac for development environment of a project. I ran dockerized development environment based on docker-compose, and I found it to be painfully slow. You can find numerous posts on discussion forums like <a href="https://forums.docker.com/t/painfully-slow/32078">this,</a> <a href="https://www.reddit.com/r/docker/comments/59u1b8/why_is_docker_so_slow_on_mac/">this,</a> <a href="https://github.com/docker/for-mac/issues/1018">this</a> etc. which prove the slowness of Docker in Mac.</p><p>In this post, I will mention some techniques that you can use to improve the performance. While you may not be able to make it fully as performant as on Linux environments, these steps will help massively.</p><h3>1. Using docker-sync</h3><p><a href="http://docker-sync.io/">Docker-sync</a> is an alternative tool to the native volumes sharing of <a href="https://docs.docker.com/docker-for-mac/">Docker for Mac.</a> It provides different <a href="https://github.com/EugenMayer/docker-sync/wiki/8.-Strategies">sync strategies</a> each with its own pros and cons. You have to choose the one that is suitable for you.</p><p>Here’s an example configuration using rsyncstrategy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/519ce254071f923ffb3e5680cb687739/href">https://medium.com/media/519ce254071f923ffb3e5680cb687739/href</a></iframe><p>After that, run the following commands in the root of your project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0da2f12cc494694af4cbadaf5ce68145/href">https://medium.com/media/0da2f12cc494694af4cbadaf5ce68145/href</a></iframe><p>You can browse the configuration guide for docker-sync.yml <a href="https://github.com/EugenMayer/docker-sync/wiki/2.-Configuration">here</a>.</p><p>You can also check out the multiple boilerplate demonstrating different strategies available in <a href="https://github.com/EugenMayer/docker-sync-boilerplate">EugenMayer/docker-sync-boilerplate</a> repository.</p><h3>2. Using cached and delegated flag in docker volumes</h3><p>In many cases, when the docker volume’s sync is very slow, it is because of the <em>perfect consistency</em> by default between host and the container and in many cases, the <em>perfect consistency </em>is unnecessary.</p><p>In many cases, there is no need for writes performed in a container to be immediately reflected on the host and in many cases, there is no need for writes performed in the host to be immediately reflected in a container.</p><p>According to the official documentation of Docker for Mac,</p><blockquote>Docker 17.04 CE Edge adds support for two new flags to the docker run <em>-v</em>, <em>--volume</em> option, <em>cached</em> and <em>delegated</em>, that can significantly improve the performance of mounted volume access on Docker for Mac.</blockquote><p>There are 3 different flags that you can use in the --volume option:</p><ol><li>consistent: perfect consistency (host and container have an identical view of the mount at all times)</li><li>cached: the host’s view is authoritative (permit delays before updates on the host appear in the container)</li><li>delegated: the container’s view is authoritative (permit delays before updates on the container appear in the host)</li></ol><p>Here’s an example using cached flag as a suffix to -v option:</p><pre>docker run -it -v /Users/ujjwal/project:/app:cached alpine command</pre><h3><strong>3. Only syncing the required files and folders</strong></h3><p>In many cases, we sync auto-generated files, platform-specific files generated during compile time or program running time etc.</p><p>For example, if you are using a node project, I can blindly bet that you have node_modules folders in megabytes. In many cases, you can install the npm dependencies in container and you don’t really have to sync that folder between host and the container.</p><p>Here’s a way to prohibit the syncing of node_modules folder.</p><pre>volumes:<br>   - &#39;./myApp:/opt/app&#39;<br>   - /opt/app/node_modules/</pre><p>Techniques like this should be used to prohibit the unnecessary syncing of files and folders and to improve the performance massively. <strong>Don’t sync what is not required.</strong></p><h3><strong>4. Optimizing development environment tooling</strong></h3><p>This may look very obvious. But in a lot of cases, you ignore the performance of development environment tooling. Spending a little bit of time may have massive improvements in performance, even more than you expect.</p><p>This actually turned out to be the most significant performance improving step for me. On my Mac, the CPU percentage of docker hyperkit process as shown on Activity Monitor reduced from 150% to 7%. I will explain the specific optimizations I did in that project.</p><p>It was a node project, node.js on the backend and React.js on the frontend.</p><p>I had to set <a href="https://github.com/paulmillr/chokidar#performance">chokidar</a>’s usePolling option as true. Otherwise, file changes were not detected in docker volumes. The reason for that is there’s an <a href="https://github.com/moby/moby/issues/18246">issue</a> in docker, so file changes are not detected in mounted volumes in Mac or Windows because filesystem events are not propagated from host to container.</p><p>By default, the polling interval is 100. I set that to 250, and it was a fair enough trade I was willing to make for performance.</p><p>Another thing that I did was to ignore watching node_modules folder. In a non-docker environment, watching node_modules was not a big performance problem. But, with chokidar’s polling in a dockerized environment, this was the deal breaker for me which made the most significant improvement in my project.</p><h3>Conclusion</h3><p>Docker for Mac has a lot of problems performance wise. But, there are ways to overcome the issue. Sometimes, it’s an issue with the tools itself but there may be ways to minimize the problems. Changing the tools and moving to better and new tools is not always the solution.</p><p>In this case, we dig deeper when the development environment was frustratingly slow and applied some tricks to create a much more performant and resource efficient development environment in docker.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dac16aa4524" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devcupboard/dockerizing-development-environment-in-mac-performance-debugging-dac16aa4524">Dockerizing Development Environment in Mac: Performance Enhancement</a> was originally published in <a href="https://medium.com/devcupboard">DevCupBoard</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Command Pattern: A different way to organize your Service layer]]></title>
            <link>https://medium.com/devcupboard/command-pattern-a-new-way-to-organize-your-domain-layer-5fe4cb8d3130?source=rss-7896e01eaa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fe4cb8d3130</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tactician]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[command-pattern]]></category>
            <dc:creator><![CDATA[Ujjwal Ojha]]></dc:creator>
            <pubDate>Wed, 20 Dec 2017 17:04:52 GMT</pubDate>
            <atom:updated>2018-12-04T07:38:30.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVxB5iMZW3j1ptKjoFwi9g.jpeg" /></figure><p>If you are like me, you probably create a Service layer where your application’s business logic resides. And, if you are like most of PHP developers, you probably create service classes like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e93f52b998bdc0f14bba719407298721/href">https://medium.com/media/e93f52b998bdc0f14bba719407298721/href</a></iframe><p>Now, you have decided to add Post liking feature to your application. Now, you add a new method to your PostService class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed422618731b8e72ac2b202141061a8b/href">https://medium.com/media/ed422618731b8e72ac2b202141061a8b/href</a></iframe><p>So, it works and doesn’t look a mess at all.</p><p>But, what if you decide to add comments features and now, you have to add more methods to the PostService. This becomes unmaintainable if we keep on adding more methods to the class.</p><p>One way to organize it is to use Command Pattern. It consists of:</p><ol><li>A command object for each action</li><li>A handler for each action which requires the command object as it’s argument</li></ol><p><strong>Command</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b98a2032e1006a1c45e34524ebc6a553/href">https://medium.com/media/b98a2032e1006a1c45e34524ebc6a553/href</a></iframe><p><strong>Handler</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/213c74cd6ff642c82f8d176534f391db/href">https://medium.com/media/213c74cd6ff642c82f8d176534f391db/href</a></iframe><p>Now, we need to call the handler and pass the command object as it’s argument. The responsibility of handing over command to handlers is done by a special kind of object called command bus.</p><p><a href="https://tactician.thephpleague.com/">Tactician</a> library provides a really awesome command bus which does all the hard work of handling over command to its specific handler object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7624fcaa315246202a225a7fe21446cc/href">https://medium.com/media/7624fcaa315246202a225a7fe21446cc/href</a></iframe><p>You can head over to it’s awesome <a href="https://tactician.thephpleague.com/">documentation</a> to learn more about it.</p><p>If you like the post and want to follow us, you can follow us on medium and our twitter handler isdevcupboard as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fe4cb8d3130" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devcupboard/command-pattern-a-new-way-to-organize-your-domain-layer-5fe4cb8d3130">Command Pattern: A different way to organize your Service layer</a> was originally published in <a href="https://medium.com/devcupboard">DevCupBoard</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elegant background jobs in PHP]]></title>
            <link>https://medium.com/devcupboard/elegant-background-jobs-in-php-c61b91bf582b?source=rss-7896e01eaa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/c61b91bf582b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[task-queues]]></category>
            <category><![CDATA[message-queue]]></category>
            <dc:creator><![CDATA[Ujjwal Ojha]]></dc:creator>
            <pubDate>Wed, 18 Oct 2017 07:28:41 GMT</pubDate>
            <atom:updated>2017-10-27T08:24:01.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYjist8ieJ4saPzrlDuftQ.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/VY1EDHABTDE">https://unsplash.com/photos/VY1EDHABTDE</a></figcaption></figure><p>For a long time, I was looking for some elegant solutions to create and run background jobs in PHP.</p><p>I joined a company which used Laravel massively and Laravel ships with an awesome <a href="https://laravel.com/docs/5.5/queues">Queue</a> system. Suddenly, I forgot how tedious and troublesome it used to be for me to write queues in PHP.</p><p>But, Laravel’s Queue seems to be tightly coupled with Laravel. We run out of such elegant solutions for applications that don’t use Laravel framework.</p><p>Bernard to the rescue. Bernard is a powerful PHP library for creating and running background jobs in PHP. According to its intro in Github repo:</p><blockquote>Bernard is a multi-backend PHP library for creating background jobs for later processing. Bernard makes it super easy and enjoyable to do background processing in PHP.</blockquote><p>But, configuring Bernard is not easy and the documentation is not clear enough. So, this is my attempt to get started with configuring Bernard.</p><h3>Concepts</h3><h4>Message</h4><p>A message is an object of any class implementing Bernard\Message which is added to background queue. It represents the job to be performed.</p><h4>Producer</h4><p>Producer is an object which sends a message to the right queue.</p><h4>Consumer</h4><p>Consumer is an object which takes messages from a queue and sends the message to the message receiver for handling the task specified in the message.</p><h4>Serializer</h4><p>A serializer is an object which is responsible for:</p><ol><li>converting the message object to JSON for persistent storage</li><li>converting the JSON back to message object for consuming the message by the Consumer.</li></ol><h4>Driver</h4><p>Drivers are pluggable message broker system responsible for actually sending the message from producers to consumers. In Bernard, a Driver implements <strong>Bernard\Driver</strong>. There are various implementations based on Redis, RabbitMQ etc. Check the <a href="http://bernard.readthedocs.io/drivers.html">Drivers page</a> in the official documentation for the full list. Here’s a simple example of constructing driver based on <a href="https://packagist.org/packages/predis/predis">predis/predis</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58f19a7ce56e60fac15e2690ac615e74/href">https://medium.com/media/58f19a7ce56e60fac15e2690ac615e74/href</a></iframe><h3>Simple Example</h3><h4>Producing Message</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31719fba5c29c2a5e697ee69814a0462/href">https://medium.com/media/31719fba5c29c2a5e697ee69814a0462/href</a></iframe><p>Here, we have created a message with name SendForgotPasswordEmail and sent it to queue emails.</p><h4>Consuming Message</h4><p>Now, we need to create a consumer which listens to the emails queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57419387a0740ad32ba98133ab3d253b/href">https://medium.com/media/57419387a0740ad32ba98133ab3d253b/href</a></iframe><h4>Consuming more than one queues</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d45cd65e35f16e5188a2d8ef5ae5f524/href">https://medium.com/media/d45cd65e35f16e5188a2d8ef5ae5f524/href</a></iframe><h3>Advanced Example:</h3><p>Suppose, we want to communicate using Message Objects of our own class like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78ec49721862aa011ae8f20804519a7c/href">https://medium.com/media/78ec49721862aa011ae8f20804519a7c/href</a></iframe><p>All good till now. But, Bernard needs to convert the message object to JSON so that it can persist the message in the appropriate queue in JSON format. By default, Bernard only supports Bernard\Message\PlainMessage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*tXo2nhLFnlANGSZ71xim9w.png" /></figure><p>By default, Bernard can only normalize Bernard\Message\PlainMessage . We need to configure custom normalizer to normalize our custom object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6b2a6e2443e02f932d29725ab1a0bdf/href">https://medium.com/media/a6b2a6e2443e02f932d29725ab1a0bdf/href</a></iframe><p>We added a new ObjectNormalizer which can normalize any object. You need to install symfony/property-access package to use this normalizer.</p><p>Now, let’s create a handler class for handling the task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ddd7d825f40989e71f984de1b266fcf/href">https://medium.com/media/0ddd7d825f40989e71f984de1b266fcf/href</a></iframe><p>Assigning a callable job handler for each message class is quite tedious. What if we could create a map of message class to its handler class like given below and load the handler on demand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc61f7d133c619dd03df1fa2250ac05f/href">https://medium.com/media/dc61f7d133c619dd03df1fa2250ac05f/href</a></iframe><p>Now, we can try to resolve the handler object from a dependency injection container. For this post, I am going to assume that the dependency injection implements <a href="https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-11-container.md">PSR-11</a> <a href="https://github.com/php-fig/container/blob/master/src/ContainerInterface.php">ContainerInterface</a>. But, the example given below will be similar for most cases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f39eabe6cb14e986e8ee9de5cd8ee44/href">https://medium.com/media/2f39eabe6cb14e986e8ee9de5cd8ee44/href</a></iframe><p>Now, here’s how our handler class will look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5915e4140a58181ebd44da0b209154f9/href">https://medium.com/media/5915e4140a58181ebd44da0b209154f9/href</a></iframe><p>Looks, pretty clean and above all <strong>Elegant.</strong></p><p>Personally, I prefer to create an abstract class AbstractMessage class which returns message name based on full class name as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcd272c55b920972ec794c789c3efeed/href">https://medium.com/media/bcd272c55b920972ec794c789c3efeed/href</a></iframe><p>You can also use attach listeners to EventDispatcher in the consumer script as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bbfd0ef2de4c6be2db068f1fc1f896c/href">https://medium.com/media/5bbfd0ef2de4c6be2db068f1fc1f896c/href</a></iframe><p>The code for the final result is available in <a href="https://github.com/devcupboard/elegant-background-job-php-demo">this repository</a>.</p><p>Please, feel free to hack around and you can comment if you have a better approach for handling the situation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c61b91bf582b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devcupboard/elegant-background-jobs-in-php-c61b91bf582b">Elegant background jobs in PHP</a> was originally published in <a href="https://medium.com/devcupboard">DevCupBoard</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A different view on Dependency Injection in Laravel]]></title>
            <link>https://medium.com/devcupboard/a-different-view-on-dependency-injection-in-laravel-c01ec690d9ee?source=rss-7896e01eaa28------2</link>
            <guid isPermaLink="false">https://medium.com/p/c01ec690d9ee</guid>
            <category><![CDATA[laravel-5]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Ujjwal Ojha]]></dc:creator>
            <pubDate>Sun, 08 Oct 2017 05:42:25 GMT</pubDate>
            <atom:updated>2017-10-08T15:27:35.954Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bR1f-NGmSsrZ2efFtIUwDA.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/vBxlL1xpSdc">https://unsplash.com/photos/vBxlL1xpSdc</a></figcaption></figure><p>This <a href="https://stackoverflow.com/a/140655">StackOverflow Answer</a> explains Dependency Injection perfectly.</p><blockquote>Basically, instead of having your objects creating a dependency or asking a factory object to make one for them, you pass the needed dependencies into the object externally, and you make it somebody else’s problem.</blockquote><p>You make it somebody’s else’s problem to inject the dependencies of your class. In the context of Laravel, this “somebody” is <a href="https://laravel.com/docs/5.5/container">Service Container</a>. In Laravel, Service Container is responsible for injecting the dependencies of your class via the constructor.</p><p>Anytime, you ask for a dependency in a class like a controller, the service container is responsible for:</p><ol><li>Automatically detecting the dependencies in constructor</li><li>Constructing the dependencies if needed</li><li>Creating the object by passing the dependencies via the constructor</li></ol><p>Let’s take a very simple case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11807396672646b6fbb5b588cb43e1f9/href">https://medium.com/media/11807396672646b6fbb5b588cb43e1f9/href</a></iframe><p>Suppose, you have a class UserController which requires UserRepository as a constructor dependency.</p><ol><li>The Service Container uses PHP’s <a href="http://php.net/manual/en/class.reflectionclass.php">ReflectionClass</a> to detect the fact that UserRepository should be resolved first.</li><li>Then, it constructs an instance of UserRepository.</li><li>Then, it constructs the instance of UserController class.</li></ol><p>I am baffled by so many Laravel Developers not knowing this simple but powerful technique of how the dependencies are resolved and injected. This is a very powerful technique and it can be used to resolve complex object dependencies.</p><p>If for some reason, you don’t want Laravel automatically constructing an object, you can also tell the Laravel Service Container how to construct the object by passing a callback which can be used to create a dependency.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5910dcd5db715f030823facbdda804f8/href">https://medium.com/media/5910dcd5db715f030823facbdda804f8/href</a></iframe><p>You need to create a Service Provider to register the above service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/812beffe882ef34a7326aae8b1bbc86f/href">https://medium.com/media/812beffe882ef34a7326aae8b1bbc86f/href</a></iframe><p>Anytime, `<strong>My\Service</strong>` needs to be resolved, the callback is called which is responsible for returning an object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e94f2d4f025803dc31da372253269fe5/href">https://medium.com/media/e94f2d4f025803dc31da372253269fe5/href</a></iframe><h4><strong>Real world Example</strong></h4><p>Suppose, your application requires Facebook’s PHP SDK to access Facebook’s API and your controller is like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b7746e332ede5b493541452e3b6daab/href">https://medium.com/media/6b7746e332ede5b493541452e3b6daab/href</a></iframe><p>Now, you need to tell Service Container how to construct an instance of `<strong>Facebook\Facebook</strong>`.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bf73f523ef5ecfbd70c389d3645bb06/href">https://medium.com/media/5bf73f523ef5ecfbd70c389d3645bb06/href</a></iframe><p>Notice, I have called the method “singleton” instead of “bind”. The only difference is that services registered with “singleton” are cached and subsequent calls to resolve the service returns the cached services.</p><h4>Conclusion</h4><p>Dependency injection is a powerful technique which you can use in Laravel to simplify the creation of objects. By default, Laravel’s Service Container uses Reflection to automatically detect and resolve dependencies. But, you can specify callbacks which can be called to resolve the services.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c01ec690d9ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devcupboard/a-different-view-on-dependency-injection-in-laravel-c01ec690d9ee">A different view on Dependency Injection in Laravel</a> was originally published in <a href="https://medium.com/devcupboard">DevCupBoard</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>