<?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[Weebly Engineering Blog - Medium]]></title>
        <description><![CDATA[Check out engineering.weebly.com for more engineering stuff. - Medium]]></description>
        <link>https://medium.com/weebly-engineering?source=rss----5f44333efac2---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Weebly Engineering Blog - Medium</title>
            <link>https://medium.com/weebly-engineering?source=rss----5f44333efac2---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 20:18:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/weebly-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding the Basics of Working with Heavily Imbalanced Datasets in Machine Learning]]></title>
            <link>https://medium.com/weebly-engineering/understanding-the-basics-of-working-with-heavily-imbalanced-datasets-in-machine-learning-e89f74036fbf?source=rss----5f44333efac2---4</link>
            <guid isPermaLink="false">https://medium.com/p/e89f74036fbf</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Thomas Angsten]]></dc:creator>
            <pubDate>Wed, 18 Jul 2018 00:40:46 GMT</pubDate>
            <atom:updated>2018-07-18T00:40:45.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*D1Zi25y12aeTt0ryDfXfmw.png" /><figcaption>Image courtesy of: <a href="https://pixabay.com/en/scale-money-tax-tax-collector-2522379/">https://pixabay.com/en/scale-money-tax-tax-collector-2522379/</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>Producing a valuable classification model from a heavily imbalanced training dataset can be challenging in machine learning. In this article, I will present a simple but effective method ML engineers can use to produce an effective classification model from an imbalanced dataset. I will also outline some of the most common mistakes ML engineers make while handling heavily imbalanced datasets.</p><p>Machine learning engineers often encounter problems requiring classification of an instance into one of two categories based on available features. Common use cases include:</p><ul><li>Email spam filtering</li><li>Fraud detection</li><li>Predicting if a patient has a cancerous tumor based on an x-ray image</li></ul><p>These three examples have, in common, a positive class (spam, fraudulent, or tumor present) that is often heavily underrepresented in the population. For example, much less than one percent of users of an application will ever attempt fraudulent behavior, with the vast majority engaging in normal day-to-day usage.</p><h3><strong>Example — Imbalanced Dataset Use Case at Weebly</strong></h3><p><strong>Scenario:</strong> Imagine you’re a newly hired machine learning engineer at a company with full access to the training dataset provided below. Your first task is to develop a model that identifies the probability a user will pay as accurately as possible using the two action-based features.</p><p><strong>Primary Goal:</strong> Predict the probability of recently created freemium accounts to become subscribers to one of Weebly’s paid services in the near future.</p><p><strong>Example Dataset:</strong> Let’s assume you’ve completed the quantitative analysis of the example dataset, and learn that less than 2% of Weebly’s users are not on paid plans. Figure 1 (below) shows what such an imbalanced dataset might look like. In this figure, paid users as shown as green markers, while users who remain with the free service are shown in red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*MXOBSD9aLnsvc5j_" /><figcaption><strong>Figure 1: </strong>A schematic imbalanced dataset of converting and non-converting users, with two action-based features plotted for each user. Users who end up paying for a plan are shown in green, while those who continue using the free service are in red.</figcaption></figure><p>Each user, i.e., each data point, is embedded into a two-dimensional plane spanned from two potentially important features used to predict probability of future conversion to a paid service:</p><ul><li>User’s total number of interactions with Weebly products online (such as clicks, logins, or editing settings)</li><li>Number of hours between the user’s most recent action and now.</li></ul><p>Only 1%, or 500 out of the 50,000 data points, are positive, resulting in a heavily imbalanced dataset.</p><p><strong>NOTE:</strong><em> the model Weebly actually build takes into account a much more complicated structure of user properties and actual data. The data shown in Figure 1 is an artificial projection for illustration purposes only. We will keep using this simple “minimum projection” in the following sections for simplicity.</em></p><h3><strong>The Accuracy Trap</strong></h3><p>If you’re relatively new to machine learning, you may have only worked with well-balanced datasets in the past, and your first instinct might be to jump right in and throw a standard classifier at the training data without making any modifications.</p><p>When you train a random forest classifier on the data in Figure 1 and evaluate its performance on a test set, you find that the model is 99% accurate at predicting whether or not a user will convert. You’re pretty excited at this point, so you show some consumers of the model immediately. A bit later, these model consumers ask you to provide a confusion matrix to help them understand the types of errors your model makes. When you print the matrix out, you see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/0*NoRz1dPwcucwXgSP" /><figcaption><strong>Figure 2: </strong>The confusion matrix for a pessimistic classifier trained on a heavily imbalanced dataset. Only negative predictions are made, as this optimizes the model accuracy.</figcaption></figure><p>You realize that <strong>the model never predicts a user will convert within the entire test set of nearly 20,000 users. </strong>Instead, it takes every user, regardless of that user’s total number of actions taken and time to their last activity, and it lumps them in the ‘Not Converted’ category. Why did this happen? Doesn’t Figure 1 clearly show differences in the distributions of these two features among converters and non-converters?</p><p>The behavior of the model in the above scenario is a direct result of the nature of the model’s underlying algorithm. Standard machine learning binary classifiers usually work best when there is a balance between the number of positive and negative instances in the training set. When training occurs, the model tweaks internal parameters or generates decision boundaries in order to optimize the overall predictive accuracy on the training set. Because each instance contributes to the model’s accuracy equally, and because negative instances far outweigh the positive in number, the model finds it can maximize accuracy by simply outputting ‘Not Converted’ for every instance, regardless of its input features. In this way, all the algorithm ‘learns’ is that it’s never worth trying to identify positive instances as positive, because this risks hurting the model’s ability to correctly classify negative instances, which contribute to the overall accuracy nearly 100X more than positive instances.</p><p>For any classification model, there is almost always a tradeoff between identifying positive instances accurately, measured by ‘recall’, and identifying negative instances accurately, measured by ‘sensitivity’. A given model will be biased to optimize the accuracy parameter corresponding to the majority class. In the above example, the model’s recall ends up being (0)/(0+169) = 0%, meaning that, when presented with positive instances, the model will always fail to positively classify them. On the other hand, the sensitivity is (16,497)/(0+16,497) = 1.0, or 100%, meaning the model will always correctly classify a negative instance as negative. If the model traded a 1% increase in recall with a 1% decrease in sensitivity during training, the resulting accuracy would be (0.01*200 + 0.99*19,800)/(20,000) = 19,604/20,000 = 98.02%, or a nearly 1% decrease in the overall accuracy.</p><p>If you’ve read this far and are still thinking,</p><blockquote>“Yeah, but 99% accuracy is pretty awesome”</blockquote><p>but consider the fact <strong>the model has provided no information beyond basic statistics</strong>. You don’t need ML engineers to effectively divide the number of negative instances by the total number of instances (=0.99) and provide this as the probability of a user being a non-converter. Your analytics team did this on day one, and have already been using this degree of knowledge to inform various business decisions.</p><blockquote><strong><em>The job of an ML engineer is to go a layer deeper.</em></strong></blockquote><h3><strong>A Quick Fix — Undersampling</strong></h3><p>Before your boss finds out that your first model adds no new value to the company, you need to train a new one that can provide some useful predictions.</p><p>In a frantic Google search consisting of the words ‘classifier always outputs zero’, you find a Stack Overflow post mentioning that your binary classifier might perform better if you randomly undersample the majority class so that you end up with equal numbers of positive and negative instances in your training dataset. To make this happen, you know there are 500 converter instances in your full dataset, so you add to these 500 more instances that were randomly sampled from the collection of non-converter instances, forming a new training set. This balanced training set has 1,000 instances, exactly 50% of which are the positive class, as plotted in Figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*UFZizAcTKthXOCgq" /><figcaption><strong>Figure 3: </strong>A balanced dataset created by randomly undersampling the majority class of the dataset shown in Figure 1. Converting and non-converting users are now represented equally.</figcaption></figure><p>You train a second random forest classifier on this new dataset, and through cross validation, you discover your model is 79% accurate at predicting whether a user will convert or not. This number doesn’t sound nearly as good as 99%, but you’re happy with anything above 60% at this point. You inspect the confusion matrix to see the distribution of errors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/0*439DqPI-x3Wx4wE9" /><figcaption><strong>Figure 4: </strong>The confusion matrix for a classifier trained on a balanced dataset. The matrix is nearly symmetric across the diagonal.</figcaption></figure><p>You can tell from this matrix that the model is no longer lumping all instances into the ‘Not Converted’ category. Instead, it makes a balanced effort to identify both positive and negative class instances, as evidenced by the nearly symmetric confusion matrix. You also notice that the recall has increased to (128)/(36+128) = 78%, and the sensitivity has decreased to (135)/(42+135) = 76%. In a final test, you look at the accuracy of your model on a hold-out dataset with the original, imbalanced distribution. This seems wise, given that, when you put your model into production, it will see a heavily imbalanced dataset quite unlike the balanced set. The overall accuracy is around 76%, and one last time, you print off the confusion matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/0*CDFuxS5SGZUlZ_8E" /><figcaption><strong>Figure 5: </strong>The confusion matrix for a classifier trained on a balanced dataset when tested on a hold-out set with the original imbalanced distribution.</figcaption></figure><p>From this matrix, you can see that, even though your model can now correctly pick out 414 out of 512 of the converting users, it incorrectly predicts that 10,491 non-converting users will convert. It seems like your model made a pretty bad trade-off. In the effort to correctly identify hundreds of users, the model incorrectly identify thousands! It’s important at this point not to be dismayed, but rather <strong>step back and ask yourself, ‘what is the ultimate goal of my model?’ </strong>The answer to this question will inform the final step of working with your imbalanced dataset, which is to set the balance between correctly identifying positive cases versus negative cases.</p><h3><strong>The Inevitable Trade-off</strong></h3><p>When working on a classification problem, one can always make a trade-off between accurately predicting the positive class and accurately predicting the negative class. In the above example, undersampling the majority class made the model focus more on predicting the positive instances correctly. It did this by effectively over representing the positive case as compared to within the original sample. Undersampling is just one of many ways to facilitate this trade-off. How to set the trade-off balance depends on who will consume the model and for what purposes.</p><p>Imagine the consumers of your model suddenly tell you they want to use it to deliver discount coupons to motivate users to buy the product. They specifically mention that they don’t want to send offers to users who already seem interested in purchasing, and that they need a model that gives them a large set of users who are very unlikely to ever enter a paid service.</p><p>This is good news for you, because the second model you built using a balanced dataset is almost 80% successful at picking out the set of users who will convert. As a result of your work, you can now provide your stakeholders with a list of nearly 40,000 users that are unlikely to purchase the product. In fact, only around 96/40,000 = 0.24% of these users will end up converting. Even though your model incorrectly identifies around 24% of non-converters as converters, the model consumers don’t care about this type of error. They’re not worried about sending coupons to everyone possible, just a large group who are very unlikely to pay without external motivation. Had you delivered your initial model trained on an imbalanced dataset, you would have caused coupons to be sent to all users, even the 1% that were going to pay anyway, leading to some pretty angry stakeholders!</p><h3>In Closing…</h3><p>Working with heavily imbalanced data presents additional challenges as compared to balanced data, but an understanding of a few straightforward concepts can help one avoid common mistakes.</p><p>A standard model trained on an unmodified imbalanced dataset will likely lead to a classifier that focuses almost entirely on getting the majority class correct. A simple way to push the model to more accurately identify the minority class is to undersample the majority class in the training set.</p><p>There always will be a trade-off between overall accuracy and the ability of the classifier to identify the minority class, and the balance between these two goals should be dictated by the priorities of the use case for the model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e89f74036fbf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weebly-engineering/understanding-the-basics-of-working-with-heavily-imbalanced-datasets-in-machine-learning-e89f74036fbf">Understanding the Basics of Working with Heavily Imbalanced Datasets in Machine Learning</a> was originally published in <a href="https://medium.com/weebly-engineering">Weebly Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supporting concurrent renewable Apple Subscriptions]]></title>
            <link>https://medium.com/weebly-engineering/supporting-concurrent-renewable-apple-subscriptions-cb1596cf4553?source=rss----5f44333efac2---4</link>
            <guid isPermaLink="false">https://medium.com/p/cb1596cf4553</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[subscription]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Weebly Engineering]]></dc:creator>
            <pubDate>Tue, 07 Mar 2017 17:55:32 GMT</pubDate>
            <atom:updated>2017-03-07T18:30:14.706Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Also published on </em><a href="http://engineering.weebly.com/"><em>https://engineering.weebly.com/</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*U3SuwmoaghAFOIUEn0reKg.png" /></figure><h3><strong>Background</strong></h3><p>Until recently, the Weebly iPhone app only offered our customers the ability to upgrade their site with a non-renewable in-app purchase. After a subscription’s duration elapsed, we needed to notify the user to purchase another upgrade before their service expired.</p><p>As of October 2016, we switched to renewable subscriptions which resulted in reduced friction and improved revenue terms for renewals beyond a year.</p><p>Weebly’s business model is unique in that a single user may upgrade multiple sites concurrently. At the time of this writing, Apple’s subscription groups only allow for one active subscription per user.</p><p>Implementing Apple’s renewable subscription model is more challenging for products that diverge outside of the standard subscriber model. This article provides a high-level overview of our strategy for working within those constraints.</p><h3><strong>Determining when a user can upgrade</strong></h3><p>The app must decide at runtime whether a subscription can be purchased by a given iTunes user. If you attempt to initiate the purchase for a user who has an existing subscription, they will receive an alert stating that the item has already been purchased.</p><p>Our solution is to <a href="https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateLocally.html#//apple_ref/doc/uid/TP40010573-CH1-SW2">examine the user’s receipt locally</a>. This involves extracting the receipt from it’s PKCS #7 envelope and parsing the data from ASN.1 formatting using <a href="https://www.libressl.org/">LibreSSL</a>. We’re able to skip the authenticity validations because the local receipt is only used to determine the appropriate product identifier to display. Secure validation is performed by our server using Apple’s remote verification API.</p><p>If the current iTunes user already has an active subscription, we can either disable the upgrade from mobile or offer multiple renewable subscription groups.</p><h3><strong>Multiple Subscription Groups</strong></h3><p>The challenge presented by multiple groups is that you’ll need to determine which SKProduct to display/sell based on the user’s purchase history. This can be determined by parsing the local receipt and checking for active subscriptions in each subscription group.</p><p>Another caveat comes from attempting to keep all of your iTunes products in sync with their respective screenshots, prices, descriptions, localizations, and other product attributes. Some of this work can be mitigated by using Apple’s Transporter to automate updates.</p><h3><strong>Receipt Verification</strong></h3><p>In order to <a href="https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Introduction.html">securely verify the customer’s active subscription</a>, you’ll need to verify their Grand Unified Receipt. Apple offers two ways of securely verifying the receipt, locally and remotely.</p><p><strong>Remote App-Store Verification (Recommended)</strong></p><p><a href="https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html#//apple_ref/doc/uid/TP40010573-CH104-SW1">Apple’s docs</a> do a great job of explaining how to perform a secure remote verification so I won’t repeat all of that here. At a high-level, remote verification initiated by your server performing an API request to Apple with a receipt identifier. Security is more straight-forward because you can trust both sides of the connection.</p><p>The interesting component of Weebly’s implementation is our strategy for uniquely identifying transactions and periodically checking them for status updates.</p><p>When parsing the receipt, we must verify that the expected transaction exists in an active state and that it has not been applied to any Weebly website. All transactions contain an original_transaction_id property which is used to group related transactions.</p><p>The catch is that the original_transaction_id is only unique to the subscription group. If a user cancels their service and later applies it to another website, the original_transaction_id is no longer unique. One solution to this is to store a combination of the original_transaction_id and the purchase_date of the oldest transaction in the chain before any subscription lapses.</p><p>It is necessary to periodically re-validate receipts to detect cancellations, refunds, and upgrades. Thus, it’s important to store the receipt identifier and create a job that fetches a fresh copy of the receipt and searches for updates.</p><h3><strong>Plan Upgrades</strong></h3><p>As of iOS 10 users may upgrade their active subscriptions through their device settings. If the user doesn’t open the associated app, you won’t receive any notifications that their service needs to be promoted. This is ok if your app only offers mobile service, but you’ll need to proactively check if you offer paid functionality on more than one platform.</p><p>The periodic check must loop through all of the related transactions to observe for changes to the product_identifier for each active subscription.</p><h3><strong>Purchase Restoration</strong></h3><p>Consider the scenario where a user purchases an active subscription but your server is down. The user is charged but the service has not yet been activated.</p><p>We’re able to detect this scenario by the existence of an unfinished SKPaymentTransaction in the payment queue. When this occurs, we send a copy of the receipt identifier to our API which determines if any active transactions in that receipt have not been associated with any Weebly service.</p><p>Unfortunately, you can not attach an identifier to the SKPaymentTransaction to remember the initial selection. If unassociated transactions exist, then we must prompt the user to select which site they intended to upgrade.</p><p>This process generally happens transparently to the user, but they can also initiate a restoration through the app settings (per Apple requirements).</p><h3><strong>Testing</strong></h3><p>Apple provides a <a href="https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnectInAppPurchase_Guide/Chapters/TestingInAppPurchases.html">sandbox environment</a> for creating test purchases that expire at a faster rate. This is ideal for testing the initial purchase, but it requires special handling for periodic checks and quality assurance testing.</p><p>Purchases in the sandbox environment auto-renew up to six times. This means that your periodic receipt service needs to check for cancellations and renewals at a faster rate for sandbox testing.</p><p>Any purchases from a sandbox account remain in the account’s purchase history. This means that future purchases from the same sandbox account will share the original_transaction_id. Theoretically, this will be handled by your expiration handling from above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*3S1kWuTdw_NnQ3aVKZFZNQ.jpeg" /></figure><h3><strong>Paul Silvis</strong></h3><p>iOS Engineer at Weebly</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb1596cf4553" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weebly-engineering/supporting-concurrent-renewable-apple-subscriptions-cb1596cf4553">Supporting concurrent renewable Apple Subscriptions</a> was originally published in <a href="https://medium.com/weebly-engineering">Weebly Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PHPUnit — Mocking the File System using vfsStream]]></title>
            <link>https://medium.com/weebly-engineering/phpunit-mocking-the-file-system-using-vfsstream-5d7d79b1eb2a?source=rss----5f44333efac2---4</link>
            <guid isPermaLink="false">https://medium.com/p/5d7d79b1eb2a</guid>
            <category><![CDATA[phpunit]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[filesystem]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Bryan Ashley]]></dc:creator>
            <pubDate>Tue, 21 Feb 2017 18:54:25 GMT</pubDate>
            <atom:updated>2017-02-21T18:56:36.532Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I found myself needing to write tests for a small class that read from a json file. The class needed to read a json file, validate its existence and content, provide a method to inform the user if a certain key exists, and provide a method to retrieve a value for a given key. The class looked something like:</p><pre>&lt;?php</pre><pre>use FileNotFoundException;<br>use InvalidJSONException;</pre><pre>class JSONReader<br>{</pre><pre>  private $file_path;<br>  private $file_contents;</pre><pre>  public function __construct($file_path)<br>  {  <br>     $this-&gt;file_path = $file_path;  <br>     $this-&gt;validateFileExists();<br>     $this-&gt;validateJSON();<br>  }</pre><pre>  public function hasKey($key)<br>  {<br>     return (array_key_exists($key, $this-&gt;file_contents) === true);<br>  }</pre><pre>  public function getValue($key)<br>  {<br>     return $this-&gt;hasKey($key)        ?<br>            $this-&gt;file_contents[$key] :<br>            null;<br>  }</pre><pre>  private function validateFileExists()<br>  {<br>     if (file_exists($this-&gt;file_path) === false) {<br>        throw new FileNotFoundException(&#39;File not found&#39;);<br>     }<br>  }</pre><pre>  private function validateJSON()<br>  { <br>     if ($this-&gt;getJSONContents() === null) { <br>        throw new InvalidJSONException(&#39;Missing or invalid json&#39;);<br>     }<br>  }<br>  <br>  private function getJSONContents()<br>  { <br>     if (isset($this-&gt;file_contents) === false) {<br>        $this-&gt;file_contents = json_decode(<br>           file_get_contents($this-&gt;file_path), <br>           true<br>        );<br>     }</pre><pre>     return $this-&gt;file_contents;<br>  }</pre><pre>}</pre><p>I’d like to write tests to validate that:</p><ul><li>Exceptions are thrown when missing file or invalid json</li><li>True and false are returned when expected in hasKey()</li><li>getValue() returns a value for an existent key</li></ul><p>Testing this class in isolation can be tricky because it currently has a dependency on the file system. Storing test json files to test this class would work, but is not ideal because it leaves a dependency on the file system in your tests. As with any external resource, there might be intermittent problems with the file system and could result in some flaky tests.</p><p>This is where <a href="https://github.com/mikey179/vfsStream">vfsStream</a> shines. vfsStream is a stream wrapper for a virtual file system. Essentially it allows you to define a file system structure, and provides you a path that your tests will be able to read/write/manipulate files from. This makes testing code that uses the php native functions for file manipulation super easy! Here’s what my tests end up looking like.</p><pre>&lt;?php</pre><pre>use org\bovigo\vfs\vfsStream;</pre><pre>class JSONFileSecretProviderTest extends TestCase<br>{<br><br>   public function setUp()<br>   {<br>     // define my virtual file system<br>     $directory = [<br>       &#39;json&#39; =&gt; [<br>         &#39;valid.json&#39; =&gt; &#39;{&quot;VALID_KEY&quot;:123}&#39;,<br>         &#39;invalid.json&#39; =&gt; &#39;{&quot;test&quot;:123&#39;<br>        ]<br>     ];<br>     // setup and cache the virtual file system<br>     $this-&gt;file_system = vfsStream::setup(&#39;root&#39;, 444, $directory);<br>   }</pre><pre>  /**<br>   * @expectedException FileNotFoundException<br>   */ <br>   public function testFileNotFoundExceptionIsThrownWhenNoFile()<br>   {<br>      $json_reader = new JSONReader(<br>         $this-&gt;file_system-&gt;url() . &#39;no-file.json&#39;<br>      ); <br>   }</pre><pre>  /**<br>   * @expectedException InvalidJSONException<br>   */ <br>   public function testInvalidJSONExceptionIsThrownWhenNoFile()<br>   {<br>      $json_reader = new JSONReader(<br>         $this-&gt;file_system-&gt;url() . &#39;/json/invalid.json&#39;;<br>      );<br>   }</pre><pre>   public function testHasKeyReturnsTrueWhenKeyFoundInFile()<br>   {<br>      $json_reader = new JSONReader(<br>         $this-&gt;file_system-&gt;url() . &#39;/json/valid.json&#39;<br>      );</pre><pre>      $this-&gt;assertTrue($json_reader-&gt;hasKey(&#39;VALID_KEY&#39;));<br>   }</pre><pre>   public function testHasKeyReturnsFalseWhenKeyNotFoundInFile()<br>   {<br>      $json_reader = new JSONReader(<br>         $this-&gt;file_system-&gt;url() . &#39;/json/valid.json&#39;<br>      );</pre><pre>      $this-&gt;assertFalse($json_reader-&gt;hasKey(&#39;NON_EXISTENT&#39;));<br>   }</pre><pre>   public function testGetKeyReturnsValueInFile()<br>   {<br>      $json_reader = new JSONReader(<br>         $this-&gt;file_system-&gt;url() . &#39;/json/valid.json&#39;<br>      );</pre><pre>      $this-&gt;assertEquals(<br>         $json_reader-&gt;getSecret(&#39;VALID_KEY&#39;), <br>         123<br>      );<br>   }<br>}</pre><p>In the above example, the setUp() method defines a directory structure to have a directory json with two files named valid.json and invalid.json with their content being provided. It then calls vfsStream::setup() which takes in a root directory name, permissions for the directory, and the defined directory array. The virtual file system is stored for reference within the tests. At any point in the tests you can call $file_system-&gt;url() which will return a full file path to the root directory in your file system, it’s output will look like vfs://root/. After all setup is done, tests can pass in their virtual file paths and native functions like file_get_contents() will read from your virtual file system.</p><p>I found this approach to be much cleaner as it removes the file system dependency, gives the developer full control on what their testing file system looks like, and does not require storing any test files your tests might need. I think it becomes even more valuable when your testing code that creates files or directories because there is no clean up required afterwards!</p><p><em>Originally published on </em><a href="https://engineering.weebly.com/"><em>https://engineering.weebly.com/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d7d79b1eb2a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weebly-engineering/phpunit-mocking-the-file-system-using-vfsstream-5d7d79b1eb2a">PHPUnit — Mocking the File System using vfsStream</a> was originally published in <a href="https://medium.com/weebly-engineering">Weebly Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a United States Sales Tax Calculator: A TDD Approach]]></title>
            <link>https://medium.com/weebly-engineering/building-a-united-states-sales-tax-calculator-part-1-a-tdd-approach-f6b7d8098322?source=rss----5f44333efac2---4</link>
            <guid isPermaLink="false">https://medium.com/p/f6b7d8098322</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[calculator]]></category>
            <category><![CDATA[taxes]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Jim Rottinger]]></dc:creator>
            <pubDate>Tue, 14 Feb 2017 18:02:01 GMT</pubDate>
            <atom:updated>2018-06-04T23:20:00.817Z</atom:updated>
            <content:encoded><![CDATA[<h4>How test-driven development ensured our tax calculator always adheres to all of the Amazon Laws for online orders</h4><p><em>by Jim Rottinger, Commerce Engineer @ Weebly</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UmhqAi4Z1KPzSO7Ae3rnIA.jpeg" /></figure><p>When it comes to collecting tax on online orders, the rules that merchants have to abide by these days are complicated. Due to a set of laws being called the <a href="https://fas.org/sgp/crs/misc/R42629.pdf">Amazon Laws</a>, whether or not an online order is taxable or not depends on a number of factors, including destination, shipping origin, and tax nexus. And because these laws are imposed at the state level, each state has a different set of rules to follow. It gets even more complex when an order has to ship over state lines.</p><p>In the early days of our eCommerce platform at Weebly, we simply had a system to manually enter in the tax rates you want to apply and where to apply them. This worked fine, but it left it up to our users to research for themselves how they should be charging tax, and help with setting up taxes became one of our largest drivers of support requests. So we wanted to do better, and that meant building a system that can automatically calculate taxes on orders.</p><p>This created a very interesting software design problem and, in this post, I will be doing a deep dive into the technical approach and implementation that went into creating the automatic tax calculator. In addition to covering the topic of online sales tax, it will serve as a case study for approaching a problem with a test driven development (TDD) mindset.</p><h4>United States Sales Tax Laws</h4><p>Before getting into the technical approach, it is worthwhile to quickly go over the sales tax laws that our service will have to abide by.</p><ul><li><strong><em>Nexus</em></strong> — In the United States, a business is only required to collect taxes in states that they have a physical presence in. A physical presence can be constituted by an office, store location, warehouse, or anything else of that like.</li><li><strong><em>Destination vs. Origin</em></strong> — If an order is crossing state lines, or even regional lines, should the tax rate at the destination location or the origin location be applied to the order? It turns out that states have different rules for determining this. Some states are <em>origin-based</em>, meaning the tax rate at the origin location should be applied, while others are <em>destination-based</em>.</li><li><strong><em>Interstate vs. Intrastate</em></strong> — Believe it or not, a state can be both destination-based and origin-based conditional upon whether the order is shipping interstate or intrastate. Interstate means it is crossing state lines and intrastate means it is shipping to a location within the same state. A state can be intrastate origin-based but interstate destination-based.</li><li><strong><em>Taxes on Shipping &amp; Handling</em></strong> — Should the cost of shipping and handling be taxed? Once again, that is up to the state. Some say no taxes on shipping, some say charge tax, and some others treat shipping and handling as individual entities such that the handling should be taxed but not the shipping (but if they are listed as the same line item, charge tax). For the purposes of this discussion, we will assume shipping and handling are always listed together.</li><li><strong><em>Special Cases</em></strong> — Despite all of the possible combinations of the above rules, some states still do not fit the mold and are thus considered special cases. One example is California which has a special rule for charging district tax. California is intrastate destination-based, but the additional district tax should only be applied if there is nexus at the destination.</li></ul><p>To help visualize all of the above rules, a flowchart has been created and can be seen in Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*2SidihEALvjwOvbb." /></figure><p>Figure 1 — Flowchart to correctly determine the tax on an order within the United States</p><h4>Technical Approach</h4><p>Whenever writing software to be used as a service such as this tax calculator, considering what the interface to your service will look like can be a huge influence in the design of your software. It will also help us create our tests. In this case, we are interested in taking an order, an origin, and a destination, and then returning a tax rate to apply to the order. In other words, something like this:</p><pre>$taxRate = TaxCalculator-&gt;getTaxRate($origin, $destination);<br>$tax = $currentOrder-&gt;getSubtotal() * $taxRate;</pre><p>There is our basic use case. However, it does not yet include all of the information we need to properly calculate the tax. As was explained above, we also need the tax nexus. To handle this, we can construct an instance of the tax calculator that takes in the addresses to use as the nexus.</p><pre>$taxNexus = [<br> [<br>   &#39;city&#39; =&gt; &#39;San Francisco&#39;,<br>   &#39;state&#39; =&gt; &#39;CA&#39;,<br>   &#39;postal_code&#39; =&gt; &#39;94107&#39;,<br>   &#39;country&#39; =&gt; &#39;US&#39;<br> ],<br> [<br>   &#39;city&#39; =&gt; &#39;New York&#39;,<br>   &#39;state&#39; =&gt; &#39;NY&#39;,<br>   &#39;postal_code&#39; =&gt; &#39;10001&#39;,<br>   &#39;country&#39; =&gt; &#39;US&#39;<br> ]<br>];</pre><pre>$taxCalculator = new TaxCalculator($origin, $destination, $taxNexus);<br>$taxRate = $taxCalculator-&gt;getTaxRate();<br>$tax = $currentOrder-&gt;getSubtotal() * $taxRate;</pre><p>This initial pass is not meant to perfect. For instance, we are eventually going to want to have a standard address format, as well as a way to lookup tax rates. But for now, this gives us an idea of how our service is going to be used.</p><h4>Defining the Test Cases</h4><p>At this point, we have a flowchart to implement and a rough idea of the interface to our service. This is enough information to define some test cases so that we can develop in a test-driven manner.</p><p>In order to have 100% test coverage, we should test each possible path in the flowchart. To keep this simple, lets exclude the California special case. That gives us the following 9 paths to test:</p><ol><li>There is no nexus at the order destination. Do not charge tax</li><li>Intrastate origin-based with no taxes on shipping</li><li>Intrastate origin-based with taxes on shipping</li><li>Intrastate destination-based with no taxes on shipping</li><li>Intrastate destination-based with taxes on shipping</li><li>Interstate origin-based with no taxes on shipping</li><li>Interstate origin-based with taxes on shipping</li><li>Interstate destination-based with no taxes on shipping</li><li>Interstate destination-based with taxes on shipping</li></ol><p>We know this will be 100% test coverage because there are four binary decisions in our flowchart. This gives us 2⁴, or 16, test cases. However, since the first decision has a termination case, we only need to test it one time, resulting in 7 of the possible permutations being short-circuited. Thus leaving us with 16–7 = 9 cases.</p><p>Now, using the same interface as we saw above, we can write our tests.</p><pre>/**<br> * <a href="http://twitter.com/dataProvider">@dataProvider</a> taxCalculatorData<br> */<br>public function testTaxCalculatorRates($destination, $origin, $nexus, $expectedRate)<br>{<br> $taxCalculator = new TaxCalculator($destination, $origin, $nexus);</pre><pre> $taxRate = $taxCalculator-&gt;getRate();</pre><pre> $this-&gt;assertEquals($expectedRate, $taxRate-&gt;tax_rate, &#39;&#39;, 0.00001);<br>}</pre><pre>/*<br> * Data provider. Data should be an iterable with data in the<br> * format of:<br> * [0] — $destination<br> * [1] — $origin<br> * [2] — $nexus<br> * [3] — $expectedRate<br> *<br> * <a href="http://twitter.com/return">@return</a> array<br> */<br>public function taxCalculatorData()<br>{<br> return [<br> //out of nexus<br> [<br> &#39;destination&#39; =&gt; [<br>   &#39;country_code&#39; =&gt; &#39;US&#39;,<br>   &#39;region&#39; =&gt; &#39;NJ&#39;,<br>   &#39;postal_code&#39; =&gt; &#39;08075&#39;<br> ],<br> &#39;origin&#39; =&gt; [<br>   &#39;country_code&#39; =&gt; &#39;US&#39;,<br>   &#39;region&#39; =&gt; &#39;CA&#39;,<br>   &#39;postal_code&#39; =&gt; &#39;94107&#39;<br> ],<br> &#39;nexus&#39; =&gt; [<br>   [<br>     &#39;country_code&#39; =&gt; &#39;US&#39;,<br>     &#39;region&#39; =&gt; &#39;CA&#39;,<br>     &#39;postal_code&#39; =&gt; &#39;94109&#39;<br>   ]<br> ],<br> &#39;expectedRate&#39; =&gt; 0.00<br> ],</pre><pre>//in nexus, intrastate, state is origin based, charge shipping tax<br> [<br> &#39;destination&#39; =&gt; [<br>   &#39;country_code&#39; =&gt; &#39;US&#39;,<br>   &#39;region&#39; =&gt; &#39;AZ&#39;,<br>   &#39;postal_code&#39; =&gt; &#39;85372&#39;<br> ],<br> &#39;origin&#39; =&gt; [<br>   &#39;country_code&#39; =&gt; &#39;US&#39;,<br>   &#39;region&#39; =&gt; &#39;AZ&#39;,<br>   &#39;postal_code&#39; =&gt; &#39;85040&#39;<br> ],<br> &#39;nexus&#39; =&gt; [<br>   [<br>     &#39;country_code&#39; =&gt; &#39;US&#39;,<br>     &#39;region&#39; =&gt; &#39;AZ&#39;,<br>     &#39;postal_code&#39; =&gt; &#39;85040&#39;<br>   ],<br> ],<br> &#39;expectedRate&#39; =&gt; 0.0860<br> ],</pre><pre>//in nexus, intrastate, state is destination based, charge shipping tax<br> [<br> &#39;destination&#39; =&gt; [<br>   &#39;country&#39; =&gt; &#39;US&#39;,<br>   &#39;region&#39; =&gt; &#39;NY&#39;,<br>   &#39;postal_code&#39; =&gt; &#39;00501&#39; //+0.04625 tax rate<br> ],<br> &#39;origin&#39; =&gt; [<br>   &#39;country&#39; =&gt; &#39;US&#39;,<br>   &#39;region&#39; =&gt; &#39;NY&#39;,<br>   &#39;postal_code&#39; =&gt; &#39;12065&#39; //+0.03000 tax rate<br> ],<br> &#39;nexus&#39; =&gt; [<br>   [<br>     &#39;country_code&#39; =&gt; &#39;US&#39;,<br>     &#39;region&#39; =&gt; &#39;NY&#39;,<br>     &#39;postal_code&#39; =&gt; &#39;00501&#39;<br>   ]<br> ],<br> &#39;expectedRate&#39; =&gt; 0.08625<br> ],</pre><pre>  //… full test cases omitted for brevity…<br> ];<br>}</pre><p>If you are not familiar with the way PHP unit works, this will simply take the test cases provided by the dataProvider and run them through the testTaxCalculatorRates function to see if the returned rate is equal to the expected rate.</p><p>With all of our test cases written out, we can run the tests and, as you might expect, they will all fail. This is a good thing! It means we are ready to begin development of a system that will satisfy all of the cases we just defined.</p><h4>Conclusion and Learnings</h4><p>There is an ongoing holy war about the effectiveness of TDD. <a href="http://softwareengineering.stackexchange.com/questions/98485/tdd-negative-experience">Some think that it is a waste of time</a> while <a href="http://stackoverflow.com/questions/913458/whats-the-best-argument-to-convince-developers-to-learn-tdd">others believe it is a sure-fire way to avoid bugs</a>. I am not here to convince you one way or the other, but lets just take a look at where we are at in our development process.</p><ul><li>We wrote out the full requirements of our service and confirmed them with legal before development began.</li><li>We have a basic idea of what the interface into our service will look like. This will help us implement the tax calculator class.</li><li>We have defined test cases that guarantee us 100% test coverage of our service</li></ul><p>Doing these things ahead of time gives us the confidence that the code we are writing will satisfy all requirements of the system. Whether or not you are a TDD believer, we can all agree tests are useful — especially when it comes to charging money which comes along with legal liabilities. It is not something we want to break even for a few minutes. Therefore, having these tests from the start is immeasurably helpful.</p><p>Where TDD falls short, however, is that it is sometimes (if not often) impossible to foresee how the software design will change over the course of the implementation. This results in having to tweak our tests as we implement the system.</p><p><em>Originally published on </em><a href="http://engineering.weebly.com/"><em>http://engineering.weebly.com/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6b7d8098322" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weebly-engineering/building-a-united-states-sales-tax-calculator-part-1-a-tdd-approach-f6b7d8098322">Building a United States Sales Tax Calculator: A TDD Approach</a> was originally published in <a href="https://medium.com/weebly-engineering">Weebly Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamed File Zipping and Downloading in PHP]]></title>
            <link>https://medium.com/weebly-engineering/streamed-file-zipping-and-downloading-in-php-1fb59b0a5b79?source=rss----5f44333efac2---4</link>
            <guid isPermaLink="false">https://medium.com/p/1fb59b0a5b79</guid>
            <category><![CDATA[zipstream]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[upload]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[download]]></category>
            <dc:creator><![CDATA[Weebly Engineering]]></dc:creator>
            <pubDate>Thu, 02 Feb 2017 21:09:58 GMT</pubDate>
            <atom:updated>2017-02-02T21:10:59.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-pVIhzJbxpFMWr1hMHDaA.jpeg" /></figure><p><em>Originally published on </em><a href="http://engineering.weebly.com/"><em>http://engineering.weebly.com/</em></a></p><p>Did you notice that on Dropbox.com, you can select a folder and start downloading it while it’s being zipped? This on-the-fly zipping feature comes handy for both the user and the server — as a user you don’t have to wait until the files are zipped on the back end before the downloading starts, and it saves the server from creating a temporary zip file and deleting it afterwards.</p><p>In this case the browser has no idea when the streamed zip file ends or how big the whole zip file will be, so what the user will see is something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*-bwQKSgn4Tt9gNkd." /></figure><p>In the Network tab, this is what such a request looks like:</p><pre>Request Headers (excerpt):<br>accept:text/plain, */*; q=0.01<br>accept-encoding:gzip, deflate<br>content-length:205<br>content-type:application/x-www-form-urlencoded; charset=UTF-8<br> <br>Response Headers (excerpt):<br>content-disposition:attachment; filename=”batch_download.zip”<br>content-type:application/x-zip<br>content-transfer-encoding:binary<br>date:Fri, 16 Dec 2016 20:01:47 GMT<br>server:nginx<br>Status:200</pre><p>Note that the <em>content-disposition</em> option is set to <em>attachment</em>. This indicates that the browser should interpret the response as a file download, rather than attempting to display the response as a web page. For details on how this option works, please refer to <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition">this article on MDN</a>.</p><p>To implement this feature with PHP, we handle the zipping and streaming work on the back end using <a href="https://github.com/maennchen/ZipStream-PHP">ZipStream</a>. Assuming your files are on the server and can be loaded with <a href="http://php.net/manual/en/function.file-get-contents.php">file_get_contents</a> given a path:</p><p>​Under the hood, when you call <em>$zip-&gt;finish()</em>, ZipStream takes care of setting the response headers (content-disposition, content-type, etc.) and makes sure that the browser treats this response as a file download. Finally it calls <em>fwrite</em> to send the data stream.</p><p>If your files are hosted on cloud services such as AWS/S3, you’ll need to use the appropriate method to load the file’s content, and call ZipStream’s lower-level method <em>$zip-&gt;addFile($file_name, $file_content)</em>. See the following example with AWS/S3:</p><pre>$file_name = ‘my_awesome_picture.jpg’;<br>$file = $client-&gt;getObject([<br> ‘Bucket’: ‘my_pictures_bucket’,<br> ‘Key’: $file_name<br>]);<br>$file_content = (string) $file[‘Body’];<br>// similar to above, except the second parameter being file content<br>$zip-&gt;addFile($file_name, $file_content);</pre><p>On the front end, all we need to do is to send a request with a payload of identifiers of the user-selected files and/or folders. This depends on your app. It’s also worth mentioning that this request cannot be made via Ajax <a href="http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax">because of security reasons</a> — in this case all Ajax could do is acquiring the zipped file in the form of a binary string, but cannot initiate file downloading. We have to resort to lower-level HTML <em>&lt;form&gt;</em>. Insert the following auxiliary <em>&lt;form&gt;</em> anywhere in your DOM:</p><p>​Note that although this request involves fetching a zipped file from the backend, we use a POST method here simply because the request payload can get pretty long if the user selected a load of files/folders. In that case, a GET method may end up with an <a href="http://stackoverflow.com/questions/2891574/how-do-i-resolve-a-http-414-request-uri-too-long-error">HTTP 414 error</a>.</p><p>The next thing is to load data into this form (by inserting <em>&lt;input&gt;</em>s) and submit it via Javascript:</p><pre>var $form = $(‘#downloader-form’);<br>// Append CSRF token for POST method<br>$form.append($(‘&lt;input&gt;’).attr({<br> name: ‘_token’,<br> value: ‘&lt;your_CSRF_token&gt;’<br>}));<br>// User-selected files, assuming files are identified by UUIDs<br>$form.append($(‘&lt;input&gt;’).attr({<br> name: ‘file_ids’,<br> value: [‘df491ae4–9d00–4674-b565-e4e5943f55b4’, …]<br>}));<br>$form.submit();</pre><p>A couple follow-up issues that worth mentioning:</p><p>(1) As the form submission completes, the browser interprets the response of your form as a document, but one of the response’s headers, <em>content-type</em>, indicates that the MIME type is <em>application/x-zip</em> instead of a valid document MIME type such as <em>text/html</em>. So you’ll probably see this log in your console:</p><p>Resource interpreted as Document but transferred with MIME type application/zip: “http://yoursite.com/batch-download&quot;.</p><p>This misinterpretation seems pretty reasonable, but there doesn’t seem to be a workaround for this. <em>&lt;form&gt;</em> was intended in the first place to submit a form and refresh the page to display the server response as a document.</p><p>(2) You may be tempted to listen on the <em>complete</em> event of the form submission, so that you can re-enable your Download button, for instance. However, this cannot be achieved. As a summary of discussions on this issue <a href="http://stackoverflow.com/questions/374644/how-do-i-capture-response-of-form-submit">here</a>, when you <em>post</em> a form, the form inputs are sent to the server and your page is supposed to be refreshed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*GiXi2_OynQ1h3KFe-KDkbw.jpeg" /><figcaption>Ye Tian</figcaption></figure><h3><strong>Ye Tian</strong></h3><p>Full Stack Software Engineer at Weebly</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fb59b0a5b79" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weebly-engineering/streamed-file-zipping-and-downloading-in-php-1fb59b0a5b79">Streamed File Zipping and Downloading in PHP</a> was originally published in <a href="https://medium.com/weebly-engineering">Weebly Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel-Docker Dev Environment]]></title>
            <link>https://medium.com/weebly-engineering/laravel-docker-dev-environment-afb4654009db?source=rss----5f44333efac2---4</link>
            <guid isPermaLink="false">https://medium.com/p/afb4654009db</guid>
            <category><![CDATA[weebly]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Weebly Engineering]]></dc:creator>
            <pubDate>Thu, 26 Jan 2017 17:55:51 GMT</pubDate>
            <atom:updated>2017-01-26T18:58:08.341Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A brief description of how we used docker for better development with Laravel.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6yjAtPSLTvkcdZQLnKAhw.jpeg" /></figure><p><em>Also published on </em><a href="http://engineering.weebly.com/"><em>http://engineering.weebly.com/</em></a></p><h3>Overview</h3><p>​This post is an overview of how we use Docker as our development environment in combination with Laravel at Weebly. My goal was to write this in a way that people with little to no Docker experience could easily follow along, and people with Docker experience could get some insight into how we used Docker with Laravel. If you have lots of Docker experience, much of this post might be reiterations of concepts you are already very familiar with.<br>​</p><h3>Preface</h3><p>We’ve been using the popular PHP framework <a href="https://laravel.com/">Laravel</a> for a recent project at work. Laravel’s “out of the box” approach to development is using <a href="https://laravel.com/docs/5.3/homestead">VMWare/Vagrant</a> (Homestead) — which works perfectly fine, but we were curious about using Docker/a containerized approach for a couple of different reasons:</p><p>1 — Lots of buzz around ‘containers/containerizing applications’. We were curious about all the fuss so figured we should see what it was all about.</p><p>2 — Our automation team has used/deployed apps using Docker previously, so we thought this might be an easy way to quickly spin up staging/integration environments for new services we build at Weebly. The old integration approach is very tailored to our monolith setup and no standard was in place for new services going forward.</p><p>3 — The idea of every change to our dev environment (every change to a container) being tracked in git felt like a potentially much cleaner solution than what we were doing with Vagrant. Not that you can’t do something similar with Vagrant, but the Docker container approach lends itself to this naturally.</p><p>For more insights into the differences between Vagrant and Docker, see this <a href="https://www.quora.com/What-is-the-difference-between-Docker-and-Vagrant-When-should-you-use-each-one">Quora post</a>.</p><h3>Getting Started</h3><p>​There is a neat project online called <a href="https://github.com/laradock/laradock">LaraDock</a>. This was a cool way to get the app running using Docker in a matter of minutes, and also a great reference to see what the configuration for all your different containers might look like. Unfortunately it didn’t really help us truly understand what was happening under the hood, so we ended up starting from scratch but heavily borrowing from the skeleton that LaraDock provides. Docker itself has a <a href="https://docs.docker.com/engine/getstarted/">pretty great tutorial</a> which was also an excellent resource (you can skip around to relevant sections without doing the whole tutorial).</p><p>Once we made the decision to start from scratch, the first step was figuring what containers we would break our application down into. Initially this ended up being:</p><ul><li><strong>nginx</strong>: our web server</li><li><strong>HHVM</strong>: to run php</li><li><strong>Postgres</strong>: our database</li><li><strong>workspace</strong>: to run things like phpunit/artisan commands/etc</li></ul><p>Why separate all of these things? Why not have everything in one place? The beauty of the containerized approach is the modularity you get. With our setup broken down into these separate containers, we could easily swap in <strong>PHP-FPM</strong> for <strong>HHVM</strong>, or <strong>MySQL</strong> for <strong>Postgres</strong> down the road (without touching any of the other containers). In fact, we actually ended up doing that PHP-FPM/HHVM swap with the release of PHP7. Also, to even more closely mimic our production environment over time we ended up with the following containers by the end as well:</p><ul><li><strong>memcached</strong>: our caching layer</li><li><strong>RabbitMQ</strong>: the queueing service we use in production</li><li><strong>artisan</strong>-queue: a container acting as a consumer node for our queue</li><li><strong>web-socket</strong>: a container running node.js and socket.io for some web socket functionality baked into our application</li></ul><h3>​A Closer Look At Containers</h3><p>​So we’ve decided on our various containers now, how do we actually build them? One of the greatest things about Docker are the thousands and thousands of images available on the <a href="https://hub.docker.com/explore/">Docker Registry</a>. For many containers, your exact solution might already exist somewhere in the Docker universe. In our case, we often wanted to pull down an existing image and then build on top of that, which Docker lets us do.</p><pre>FROM rabbitmq<br> <br># enable rabbitmq management plugin<br>RUN rabbitmq-plugins enable --offline rabbitmq_management</pre><p>In the above Dockerfile we are simply pulling <a href="https://hub.docker.com/_/rabbitmq/">this RabbitMQ Docker image</a> from the Docker Registry, and adding our own command to enable a rabbitmq admin tool. For many containers you might not even need a Dockerfile since your exact solution might be available already, but often there is lots of tinkering needed on top of an existing image. Take a look at our PHP-FPM 7.0 Dockerfile for example:</p><pre>FROM php:7.0-fpm<br> <br># Install &quot;curl&quot;, &quot;libmemcached-dev&quot;, &quot;libpq-dev&quot;, &quot;libjpeg-dev&quot;,<br>#         &quot;libpng12-dev&quot;, &quot;libfreetype6-dev&quot;, &quot;libssl-dev&quot;, &quot;libmcrypt-dev&quot;,<br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y --no-install-recommends \<br>        curl \<br>        libmemcached-dev \<br>        libz-dev \<br>        libpq-dev \<br>        libjpeg-dev \<br>        libpng12-dev \<br>        libfreetype6-dev \<br>        libssl-dev \<br>        libmcrypt-dev<br> <br># Install the PHP mcrypt extension<br>RUN docker-php-ext-install mcrypt<br> <br># Install the PHP pdo_pgsql extension<br>RUN docker-php-ext-install pdo_pgsql<br> <br># Install bcmath extension<br>RUN docker-php-ext-install bcmath<br> <br># Install the PHP gd library<br>RUN docker-php-ext-configure gd \<br>        --enable-gd-native-ttf \<br>        --with-jpeg-dir=/usr/lib \<br>        --with-freetype-dir=/usr/include/freetype2 &amp;&amp; \<br>    docker-php-ext-install gd<br> <br># Install the php memcached extension<br>RUN curl -L -o /tmp/memcached.tar.gz &quot;<a href="https://github.com/php-memcached-dev/php-memcached/archive/php7.tar.gz">https://github.com/php-memcached-dev/php-memcached/archive/php7.tar.gz</a>&quot; \<br>    &amp;&amp; mkdir -p memcached \<br>    &amp;&amp; tar -C memcached -zxvf /tmp/memcached.tar.gz --strip 1 \<br>    &amp;&amp; ( \<br>    cd memcached \<br>    &amp;&amp; phpize \<br>    &amp;&amp; ./configure \<br>    &amp;&amp; make -j$(nproc) \<br>    &amp;&amp; make install \<br>    ) \<br>    &amp;&amp; rm -r memcached \<br>    &amp;&amp; rm /tmp/memcached.tar.gz \<br>    &amp;&amp; docker-php-ext-enable memcached<br> <br># Install opcache<br>RUN docker-php-ext-install opcache &amp;&amp; docker-php-ext-enable opcache<br> <br>ADD ./laravel.ini /usr/local/etc/php/conf.d<br>ADD ./laravel.pool.conf /usr/local/etc/php-fpm.d/<br> <br>RUN rm -r /var/lib/apt/lists/*<br> <br># Permissions<br>ARG PUID=5082<br>RUN usermod -u ${PUID} www-data<br> <br>ADD start.sh /start.sh<br>RUN chmod +x /start.sh<br> <br>USER www-data<br> <br>WORKDIR /var/www/laravel<br> <br>CMD [&quot;/start.sh&quot;]</pre><p>There is a lot going on there but if you’ve ever installed and gotten a PHP application running on a linux machine, most of this is probably familiar. One thing to note is you can specify a file to run when the container gets created (running the Dockerfile itself just builds the image) with the following command:</p><pre>​CMD <strong>[</strong>“/start.sh”<strong>]</strong></pre><p>​And your <strong>start.sh</strong> script might run migrations or anything else that needs to happen when the container is spun up.</p><h3>Our docker-compose</h3><p>​After getting our various containers building individually, it was now time to have a structured way to spin up all relevant containers at once with the appropriate configuration options. One great way to do this is with a <a href="https://docs.docker.com/compose/compose-file/">docker-compose</a> file. Docker-compose is an easy way to manage your Docker services/networks/volumes all in one place without having to memorize long CLI commands. For example, when you spin up a container, you may want to copy some log files to a location on your local file system, map docker network ports to your local machine’s ports, or more. Instead of running a terminal command that might look like:</p><pre>docker run nginx -i -p 22 -p 8000:80 -m /data:/data -t &lt;foo/live&gt; /bin/bash</pre><p>We could have all this fun stuff defined in our docker-compose.yml. Below is an example of what our docker-compose.yml file might look like.</p><pre>version: &#39;2&#39;<br> <br>services:<br>nginx:<br>        build:          ## define root folder of Dockerfile<br>            context: ./nginx<br>        ports:<br>           - &quot;8000:80&quot;  ## Map Docker port 80 to Local port 8000<br>            - &quot;443:443&quot; ## Map Docker port 443 to Local port 443<br> <br>        ...more_configuration:<br>…define more containers</pre><p>Now that we have all our docker container configurations in one place we can simply run <strong>docker-compose up</strong>, and it will automatically spin up our containers defined in our <em>docker-compose.yml</em> with the appropriate configurations. This is great because now you have a file you can commit to source control so all developers have the same docker network configuration. Ultimately, our <em>docker-compose.yml</em> had a lot more going on than in the example above. Below is a slightly meatier version.</p><pre>version: &#39;2&#39;<br> <br>services:<br>nginx:<br>        build:<br>            context: ./nginx<br>            args:<br>               - PHP_UPSTREAM=php-fpm<br>        volumes_from:<br>           - volumes_source<br>        volumes:<br>           - ./logs/nginx/:/var/log/nginx<br>        links:<br>           - php-fpm<br>        ports:<br>           - &quot;80:80&quot;<br>            - &quot;443:443&quot;<br> <br>php-fpm:<br>        build:<br>            context: ./php-fpm<br>        volumes_from:<br>           - volumes_source<br> <br>postgres:<br>        build: ./postgres<br>        volumes_from:<br>           - volumes_data<br>        environment:<br>            POSTGRES_DB: our_groovy_db<br>            POSTGRES_USER: mogley<br>            POSTGRES_PASSWORD: not_telling<br> <br>…more containers<br> <br>### Laravel Application Code Container ######################<br> <br>    volumes_source:<br>        image: tianon/true<br>        volumes:<br>           - ../base/:/var/www/laravel<br> <br>### Data Container ################################<br> <br>    volumes_data:<br>        image: tianon/true<br>        volumes:<br>           - ./data/postgres:/var/lib/postgresql/data<br>            - ./data/rabbitmq:/var/lib/rabbitmq/mnesia</pre><p>As you can see there are many more configuration options you can specify on each of your containers. Also of notable interest are the <strong>volumes_source</strong> container and the <strong>volumes_data</strong> container. These are special containers known as data volumes and in our case we used them to:</p><ol><li>Sync code from local machine to our docker network and share said code across containers</li><li>Persist data beyond the lifespan of a container</li></ol><p>Here is Docker’s longer/better explanation of data volume containers:</p><ul><li>Volumes are initialized when a container is created. If the container’s base image contains data at the specified mount point, that existing data is copied into the new volume upon volume initialization</li><li>Data Volumes can be shared and reused among containers</li><li>Changes to a data volume are made directly</li><li>Changes to a data volume will not be included when you update an image</li><li>Data volumes persist even if the container itself is deleted</li></ul><p>In addition to providing structure to your Docker network, <em>docker-compose</em> is also a great way to separate configurations for your dev environment and whatever other environments you may use in conjunction with docker (staging/integration/production). You can have separate docker-compose files, i.e. <em>docker-compose.dev.yml</em>, <em>docker-compose.integration.yml</em>, and you can have a base <em>docker-compose.yml</em> that they inherit from. This is especially useful if your integration environments ports differ from your local machine, or if you want to pass in certain environment variables only to one setting.<br>​</p><h3>Final Notes</h3><p>Docker has definitely had some pain points, and it’s still a growing community. There is lots of new terminology to learn entering into the Docker/Container world. Overall, our development team that adapted this approach has been extremely happy with the decision. Some reasons (some reiterating here):</p><ul><li>Devs feel like they have a much better understanding of their infrastructure using Docker. We’re forced to have a better understanding of each service that is interacting with our application.</li><li>Devs feel a little more able to debug infrastructure related issues (without bugging those ops guys!).</li><li>Potential for more closely related prod/dev environments.</li><li>Container/service configuration in source control is amazing (I know this is not necessarily new, but certainly not common practice when using Vagrant/Homestead as far as I’m aware)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*mNIzW9fgeID-AWFMjoPN5g.jpeg" /><figcaption>Rohan Sahai</figcaption></figure><h3>Rohan Sahai</h3><p>Full Stack Software Engineer at Weebly</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afb4654009db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weebly-engineering/laravel-docker-dev-environment-afb4654009db">Laravel-Docker Dev Environment</a> was originally published in <a href="https://medium.com/weebly-engineering">Weebly Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>