<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Dayle Rees]]></title><description><![CDATA[Laravel evangelist, design enthusiast, technical author, colour-scheme engineer and all-round nerd. Here you'll find a bunch of articles about development and other exiting things!]]></description><link>https://daylerees.com/</link><generator>Ghost 0.8</generator><lastBuildDate>Thu, 21 Sep 2023 22:37:29 GMT</lastBuildDate><atom:link href="https://daylerees.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[New Home Office]]></title><description><![CDATA[<p>I’ve had a few people on Twitter asking for further details on my new home-office setup. So I thought I’d give a rundown of what I’ve bought and why I chose it while it’s fresh in my mind.</p>

<p><strong>Warning, there are lots of high-quality images in</strong></p>]]></description><link>https://daylerees.com/new-home-office/</link><guid isPermaLink="false">88f88212-01cc-478f-b283-0113e601636a</guid><category><![CDATA[desk]]></category><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Sun, 09 Dec 2018 14:01:26 GMT</pubDate><content:encoded><![CDATA[<p>I’ve had a few people on Twitter asking for further details on my new home-office setup. So I thought I’d give a rundown of what I’ve bought and why I chose it while it’s fresh in my mind.</p>

<p><strong>Warning, there are lots of high-quality images in this post. So run away now if you're on mobile data!</strong></p>

<p>Here’s the before picture.</p>

<p><img src="https://daylerees.com/content/images/2018/12/IMG_0480.png" alt="Before Picture"></p>

<p>I don’t have the full details anymore, but it was a couple of cheap £10 IKEA desks and a cheap office chair. It certainly did the trick, but wasn’t fully stable and not the most comfortable setup for long-term use.</p>

<p>Here are the pictures of the improved office.</p>

<p><img src="https://daylerees.com/content/images/2018/12/full_view-1.png" alt="Full Desk">
<img src="https://daylerees.com/content/images/2018/12/side_view.png" alt="Other Wall"></p>

<p>Let’s put the pieces together.</p>

<h2 id="customkarlbydesk">Custom Karlby Desk</h2>

<p>First up we have the desk.</p>

<p><img src="https://daylerees.com/content/images/2018/12/IMG_6457.png" alt="Empty Desk"></p>

<p>This one is a bit of an IKEA hack. I wouldn’t call it a budget option, but compared to the price you’d pay for a whole walnut desk then I think it’s a major win.</p>

<p>The top of the desk is actually an <a href="https://www.ikea.com/gb/en/products/kitchen-products/worktops-worktops-accessories/karlby-worktop-walnut-art-00335201/">IKEA kitchen worktop called the Karlby</a>. In a two and a half meter length (which happened to be perfect for the wall I was placing it against, nice!) it cost a total of £150. IKEA is able to keep it this low because it’s actually half walnut and half chipboard. The underside is made of the cheaper wood substitute, leaving the topside as the more aesthetically pleasing part. It’s still really sturdy, heavy and feels like great quality.</p>

<p>The legs I took from my existing tables and screwed them to this one. You can, however, buy them separately from IKEA. The <a href="https://www.ikea.com/gb/en/products/desks/table-tops-legs/adils-leg-silver-colour-art-10217971/">product type is called Adils</a> and they cost £2.50 each. There are some nicer legs or other colors if you fancy, but I like the plain black, and I already had some to spare. I decided to place one at each corner, and an extra one in the center back for support, right near the monitor arms which is the primary point of stress. Hopefully, this extra leg will stop the table top from dipping over time but allows the front to be open and clean.</p>

<p>Underneath the desk I have two <a href="https://www.ikea.com/gb/en/products/small-storage-organisers/cable-management-accessories/signum-cable-trunking-horizontal-silver-colour-art-30200253/">Signum again from IKEA</a>, they screw in easily, and contain all of my cables and power strips for the setup, giving the appearance of no cables at all, hurray!</p>

<h2 id="monitors">Monitors</h2>

<p>The monitors I had already, but they are two <a href="https://www.amazon.co.uk/inch-Dell-P2415Q-IPS-Monitor/dp/B00QAJ2MOM/ref=sr_1_2?ie=UTF8&amp;qid=1544364161&amp;sr=8-2&amp;keywords=dell+p2415q">Dell P2415Q</a> which are 24” 4K monitors. I personally like smaller monitors as I waste a lot of space on a 27” and up, and I need the 4K (60hz) element because if I was to try working on a 1080p I’d just end up defaulting back to the MacBook screen. I just can’t work on a screen without smooth fonts anymore.</p>

<p><img src="https://daylerees.com/content/images/2018/12/IMG_3452.png" alt="Monitors"></p>

<p>The two screens were around £200 each when I bought them a year or so ago, which I thought was an incredible price at the time.</p>

<p>The monitors are mounted on some <a href="https://www.amazon.co.uk/VonHaus-Monitor-Ergonomic-Rotation-Dimensions/dp/B076QGMJBY/ref=sr_1_2_sspa?ie=UTF8&amp;qid=1544364206&amp;sr=8-2-spons&amp;keywords=monitor+arms&amp;psc=1">cheap monitor arms</a> that I found on Amazon ages ago. I think it was £20 or so at the time.</p>

<h2 id="microphonecamera">Microphone &amp; Camera</h2>

<p>I’ve been considering trying some Twitch workshops or screencasting, that along with the fact that I’ll soon be working with a remote team meant that I was willing to pay a little more for this part of the setup.</p>

<p><img src="https://daylerees.com/content/images/2018/12/IMG_3942.png" alt="Yeti">
<img src="https://daylerees.com/content/images/2018/12/IMG_2133.png" alt="Camera"></p>

<p>I bought the <a href="https://www.amazon.co.uk/Blue-Microphones-Yeti-Microphone-Blackout/dp/B00N1YPXW2/ref=sr_1_1_sspa?ie=UTF8&amp;qid=1544364241&amp;sr=8-1-spons&amp;keywords=yeti+blue&amp;psc=1">Yeti microphone</a> due to its reputation, it was also on a Black Friday deal with <a href="https://www.amazon.co.uk/Logitech-Stream-Streaming-3-month-License/dp/B01L6L52K4/ref=sr_1_1?ie=UTF8&amp;qid=1544364269&amp;sr=8-1&amp;keywords=logitech+c922">the Logitech C922</a> (a favored streamer webcam) for £100. I could have bought a cheaper boom arm, but decided to go for <a href="https://www.amazon.co.uk/Blue-Microphones-Compass-Tube-Style-Broadcast/dp/B078MLBGRM/ref=sr_1_2?ie=UTF8&amp;qid=1544364303&amp;sr=8-2&amp;keywords=blue+compass">the Blue Compass</a>, which is made especially for the Yeti and hides the cables inside the arm, giving it a cleaner appearance. This boom arm, the shock mount, and pop filter added an extra £150 to the cost of the audio setup, but I’m really pleased with the result.</p>

<h2 id="speakers">Speakers</h2>

<p>These are a pair of <a href="https://www.amazon.co.uk/Bose-Companion-Multimedia-Speaker-System/dp/B00CL83JVQ/ref=sr_1_3?ie=UTF8&amp;qid=1544364328&amp;sr=8-3&amp;keywords=bose+computer+speakers">Bose desktop speakers</a>. There’s nothing that exciting about them really. I bought them a while ago for £100 because I use Bose earphones on my commute and have found them to be good quality.</p>

<p><img src="https://daylerees.com/content/images/2018/12/IMG_2161.png" alt="Speakers"></p>

<p>These desktop speakers, however, are nothing to write home about. Very standard quality and won’t blow anyone away! Of course, they are rarely used to to the other audio output option which I’ll describe next.</p>

<h2 id="headphonesamp">Headphones &amp; Amp</h2>

<p>I’m a huge fan of music, and I listen to it heavily while working. I’ve always been curious about the ‘audiophile’ setups, so when I saw that the Sennheiser HD6XX’s were <a href="https://www.massdrop.com/buy/massdrop-sennheiser-hd6xx">available for $200 on Massdrop</a> then I gave in.</p>

<p><img src="https://daylerees.com/content/images/2018/12/IMG_0386.png" alt="HD6XX"></p>

<p>The 6XX’s are effectively a re-colored version of the well-respected HD650’s. These are an audiophile favorite that normally start at £400. So to get them at $200 (around £157) is an incredible offer.</p>

<p>Now the 6XX’s are high impedance headphones, so you’re not going to get the benefit of them when using a standard headphone output, and so a headphone amp was required to complete the setup. I also chose to add a DAC to the mix as the MacBooks own is rather limited.</p>

<p>After some research, I decided to go for what is lovingly called ‘The Schiit Stack’. And yes, you do say it like that. It’s <a href="https://www.schiit.com/">an American company</a> with a big sense of humor, but not when it comes to the quality of their products.</p>

<p><img src="https://daylerees.com/content/images/2018/12/IMG_0397.png" alt="Schiit Stack"></p>

<p>I’ve gone with the Magni/Modi 3 and an interpose connecting the two. This is enough to fully power the headphones, and now my music sounds incredible! I highly recommend downloading some FLAC audio (lossless, CD-like) to really feel the difference.</p>

<h2 id="keyboardmouse">Keyboard &amp; Mouse</h2>

<p>This keyboard is my baby. If the house set on fire I’d save my pets and then come back for the keyboard. This definitely isn’t a cheap option, but it was a bit of a passion project that I invested in a while ago. Please forgive me, I’m a coder without kids and loves tech! Of course, I’m going to play with pricey gadgets!</p>

<p><img src="https://daylerees.com/content/images/2018/12/IMG_7263.png" alt="Keyboard"></p>

<p>The keyboard is a <a href="https://www.amazon.co.uk/Mechanical-Keyboard-Keycaps-Cherry-Mx-Clear/dp/B00OFM6F80">Vortex Pok3r</a> (without LEDs) but you probably couldn’t tell from looking at it. Pretty much only the PCB and switches remain stock. The Pok3r is a 60% keyboard, that has several layers of hardware macroing built into it. Meaning you can program macros and shortcuts without needing to install any software on the device you’re using it on. They are stored in the memory of the keyboard.</p>

<p>A 60% keyboard doesn’t have a number pad, home/insert button area, arrow keys, or an F-key row. Instead, you use combinations to replace these. For example, instead of arrow keys I use caps lock (bound to function for me) and I, J, K, and L. It takes a little while to retrain, but it keeps your fingers closer together, and once I had gotten used to it, I found it great to use!</p>

<p>It’s got Cherry MX Brown (silent) switches, but that does not mean that it’s a silent keyboard. You still have the sound of the plastic keycaps hitting the board underneath, so don’t consider this keyboard if you need to work in a quiet office environment!</p>

<p>The keycaps are Tai-Hao Hawaii PBT. I just love the colors. Anyone who knows me will know I dress really boring. Mostly black. In fact, I wear exclusively black T-shirts, but those who know of my side projects will know that I’m certainly no stranger to colors, and I’m absolutely obsessed with the Hawaii caps!</p>

<p>What could make pretty caps better? A pretty case! It’s a custom walnut case and wrest from Alibaba express. 60% keyboards have lots of alternate casing options, so it’s not difficult to find one that you like. I’ve also purchased a nice orange custom braided USB cable to finish off the look.</p>

<p>All in all this little piece of luxury cost around £240, but it makes me smile every time I use it!</p>

<p>For the mouse, I wasn’t all that bothered in the choice. I have a gaming PC setup in another room and it’s mostly Corsair, so I went with Corsair’s cheapest gaming mouse. I believe it cost £25. I can’t stand the Apple mice, they cripple my hand!</p>

<p><img src="https://daylerees.com/content/images/2018/12/IMG_4020.png" alt="Mouse"></p>

<h2 id="mac">Mac</h2>

<p>Well, this is where the budget has to go up a bit. I used to be a Linux user, but around 6 years ago I moved to a Mac, and I find it hard to drift from the aesthetics.</p>

<p>Normally I buy a Mac every few years, and I eat up the cost for the sake of it being the key part of the setup I use to further my career as an engineer. However, I’m becoming increasingly disgusted at the prices that Apple is willing to charge their customers for minor improvements, and there’s a chance I might switch back to Linux in a few years.</p>

<p><img src="https://daylerees.com/content/images/2018/12/IMG_1184.png" alt="Mac"></p>

<p>Since I buy a MacBook every few years, I need it to last. So this is the late 2017 model with the highest specs and integrated graphics (to drive the 4K screens). It cost a disgusting £2700 because Apple takes a US price, and just change the symbol. They don’t seem to be aware of the existence of an exchange rate.</p>

<p>On a side note, I hate the Touch Bar, and I think it’s a useless gimmick. Especially when used in a desktop environment. The fingerprint reader, however, I can get on with that.</p>

<h2 id="plant">Plant</h2>

<p>This is a Peace Lilly from IKEA that I’ve since moved to the kitchen. We’re getting a kitten next week (pictures on demand) and lilies are poisonous to cats, so I screwed up a bit there! I’ll find a safe replacement.</p>

<h2 id="dockingstation">Docking Station</h2>

<p>The number of cables and dongles coming out of the Mac thanks to its USB-C adoption was insane! I like that we’re making the move to USB-C, but it was a bit ugly for my desk. For this reason, I emptied out my rainy-day fund and spent far too much on <a href="http://www.caldigit.com/thunderbolt-3-dock/thunderbolt-station-3-plus/">a Caldigit TS3 Plus</a>.</p>

<p><img src="https://daylerees.com/content/images/2018/12/IMG_4172.png" alt="Under Desk"></p>

<p>This is a little brick that has a load of outputs. It was the best dock that I could find, and I specifically wanted one that would provide power to the Mac, USB-A/C for all the devices I have, and to support several 4K monitors at 60hz. This was the king, but with the extended cable, it cost £300. Not something I was expecting to buy, but as the desk got prettier, I wanted it to be neater. RIP my rainy day fund!</p>

<p>The dock is tucked under my desk in the cable tidy, and a single USB-C cable runs to my Mac (resting on a Rain stand I already had) that both charges the Mac and runs the devices/audio.</p>

<p>It was expensive, but it works REALLY well. It’s a great product.</p>

<p>If I had to pick one thing annoying with it, it’s that it doesn’t always remember which of my monitors is landscape and which is portrait. If you don’t use this setup, it won’t affect you.</p>

<h2 id="chair">Chair</h2>

<p>I’ve always wanted to try a gaming chair, and if I’m going to be working from this room then now seems like a great time to do that. I decided upon a NobleChair because I like how clean and simple they look. I don’t like “the razer effect” with the crazy edges and the glowing green or other bright colors. I saved a bit of money by going for the fake leather, but the quality is super high and I think it looks great.</p>

<p><img src="https://daylerees.com/content/images/2018/12/IMG_9891.png" alt="Chair"></p>

<p>This is the NobleChair Hero (great for big folks like this chunky boy!) and it retails at £350. I picked mine up <a href="https://www.overclockers.co.uk/lp/noblechairs-hero.html">from overclockers</a>.</p>

<p>It’s worth noting that it’s really heavy and very wide. Might be a struggle to get upstairs!</p>

<h2 id="theroom">The Room</h2>

<p>When we moved into this place a little over a year ago this room was painted baby blue and bright yellow. I suspect it might have been a nursery before. It was absolutely disgusting, so it had to go!</p>

<p>I spent a week painting it a beautiful shade of Dutch Teal, and the two walls and ceiling that you can’t see are painting in a light grey-white called Rock Salt that helps lighten the room a little. I’ve always had an eye for design and a gift for pairing colors,  but that doesn’t mean that painting dark against the light was an easy task! That’s a whole other story! (Many new swear-words were invented that week.)</p>

<p>I’ve got an HUE color changing bulb in the ceiling light, so I can change it to any color I feel like, but it’s normally a nice dimmed blue shade in the evenings which looks great on the walls.</p>

<p>The Monkey Island poster was a gift from my girlfriend who knows me so well, love you Em! I’ve been a fan of LucasArts adventures since I got my first computer. We framed it in a simple IKEA frame. I might get some more for the additional walls. We’ll see!</p>

<hr>

<p>And that’s pretty much it! All in all, I think if you exclude the laptop it will have cost around £2000, spread over a length of time. It’s a lot of money, but I believe that it’s worth investing in the tools and locations that you work with/in the most. I’m very pleased with the result, and I love working in this room.</p>]]></content:encoded></item><item><title><![CDATA[Laravel Facades]]></title><description><![CDATA[An introduction to the Laravel Facade classes, how they work, and why they aren't something to be feared when writing testable code.]]></description><link>https://daylerees.com/laravel-facades/</link><guid isPermaLink="false">63917b65-e40c-474a-87a4-f1bc0af424a7</guid><category><![CDATA[Laravel]]></category><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Thu, 01 Feb 2018 22:28:26 GMT</pubDate><content:encoded><![CDATA[<p>A Facade is a name given to a type of class in the Laravel framework that enables beginner-friendly and/or aesthetically pleasing access to tools and services held within the framework’s IoC container.</p>

<p>Here’s a quick example of a database query in Laravel.</p>

<pre><code>&lt;?php

DB::table('users')-&gt;get();  
</code></pre>

<p>In the above example, we use Laravel’s fluent database abstraction layer (DBAL) to retrieve user data from the ‘users’ table of the database. It’s nice and simple. In this example, the <code>DB</code> is the facade. We’re calling the <code>table()</code> static method on the <code>DB</code> facade, and later chaining a call to <code>get()</code> to fetch the result.</p>

<p>A lot of people shy away from static methods because they apply global state to a class. In object-oriented programming, it’s preferable to store state encapsulated within an object instance. The use of static methods can be an indication of badly constructed code, including code that is difficult to test.</p>

<p>However, static methods are part of the language spec and serve their purpose. They exist for a reason. They exist to be used correctly, with the appropriate care.</p>

<p>When experienced developers first cast sight upon a Laravel Facade, their immediate reaction is often as follows.</p>

<blockquote>
  <p>Oh no! Static methods are bad. They are hard to test!</p>
</blockquote>

<p>In general, this is often true. If the code uses static methods in a poorly conceived way then the code will be difficult to test. However, Laravel has implemented static methods with due care and attention. Let’s delve further into the usage and functionality of the Facade class to further understand why it’s not an immediate risk, and shouldn’t be feared.</p>

<p>If you image a Facade to be the following:</p>

<pre><code>&lt;?php

use DatabaseManager;

class DB  
{
    public static function table($table)
    {
        return new DatabaseManager($table);
    }
}
</code></pre>

<p><em>Please note that this is <strong>not</strong> how facades work, I’m just trying to make a point.</em></p>

<p>Then we consider the usage of the facade in a basic MVC controller, as follows:</p>

<pre><code>&lt;?php

class UsersController  
{
    public function index()
    {
        return DB::table('users')-&gt;get();
    }
}
</code></pre>

<p>The code would surely function (if it were real), but we’d be unable to change the database manager. For example, we’d be unable to swap out the database manager for a mock object, that might read data from local files within our tests. This is because the <code>table()</code> becomes a static factory method, that instantiates a <code>new</code> database manager for us.</p>

<p>Experienced developers will identify this problem as a case to implement dependency injection. Here’s what that might look like.</p>

<pre><code>&lt;?php

class UsersController  
{
    private $db;

    public function __construct($db)
    {
        $this-&gt;db = $db;
    }

    public function index()
    {
        return $this-&gt;db-&gt;table('users')-&gt;get();
    }
}
</code></pre>

<p>If the database manager is injected into the class through the constructor <code>$db</code>, and then stored within, and used from a class property, then we can easily pass different database managers into the class, including any mock objects we desire to use when testing.</p>

<p><em>Note, that you’d normally <a href="https://daylerees.com/php-interfaces-explained/">type-hint an interface</a> to ensure that the database manager contains all the anticipated methods.</em></p>

<p>In Laravel, we can leverage the <a href="https://daylerees.com/container-baking/">automatic dependency resolution nature of the container</a>, to inject our database connection directly. It would look something like this:</p>

<pre><code>&lt;?php

use Illuminate\Database\DatabaseManager;

class UsersController  
{
    private $db;

    public function __construct(DatabaseManager $db)
    {
        $this-&gt;db = $db;
    }

    public function index()
    {
        return $this-&gt;db-&gt;table('users')-&gt;get();
    }
}
</code></pre>

<p>Now, in our tests, we can inject our mock by instantiating the class directly, or we can swap the database connection instance within the Laravel container, and let Laravel do its magic. (Seriously, not magic.)</p>

<p>Clearly, injection through the constructor is much more practical than a static factory method. It’s much more flexible and far better for testing.</p>

<p>However, the ‘Facade’ shown above, was not a facade at all. Let’s take a look at a simplified version of <a href="https://github.com/laravel/framework/blob/5.5/src/Illuminate/Support/Facades/Facade.php">the Laravel Facade base class</a>, which all service facades inherit from.</p>

<pre><code>&lt;?php

abstract class Facade  
{
    protected static $app;

    protected static $resolvedInstance;

    protected static function getFacadeAccessor()
    {
        throw new RuntimeException('Facade does not implement getFacadeAccessor method.');
    }

    public static function setFacadeApplication($app)
    {
        static::$app = $app;
    }

    public static function __callStatic($method, $args)
    {
        if (!static::$resolvedInstance) {
            $key = static::getFacadeAccessor();
            static::$resolvedInstance = static::$app-&gt;make($key);
        }

        $instance = static::$resolvedInstance;

        return $instance-&gt;$method(...$args);
    }
}
</code></pre>

<p>First of all, the Facade is not an implementation of the ‘Facade pattern’ in truth, it’s more of a proxy. When you call a static method on the facade, it proxies that call to a method of the same name on a service instance held within the framework’s container.</p>

<p>To clarify, both of the following act on the same database connection.</p>

<pre><code>&lt;?php

DB::table();

$db = $app-&gt;make('db');
$db-&gt;table();
</code></pre>

<p>Both call the <code>table()</code> function on the database instance stored within the Laravel container under the key ‘db’.</p>

<p>Let’s step through our simplified view of the Facade, to see how this works. First, we’ll examine the two class properties.</p>

<pre><code>&lt;?php

protected static $app;

protected static $resolvedInstance;  
</code></pre>

<p>The first static property contains a reference to the Laravel IoC container. It’s set during the framework bootstrap process using the <code>setFacadeApplication()</code> method found in the full example above. Since this static property is set on the abstract Facade, it’s also available to all extensions of this abstract.</p>

<p>The next property, <code>$resolvedInstance</code>, will be set to the service retrieved from the container, the first time the facade is used. This creates a ‘sort of’ singleton pattern. It’s a performance gain, preventing the cost of resolving the service from the container on subsequent method calls on the Facade.</p>

<pre><code>&lt;?php

protected static function getFacadeAccessor()  
{
    throw new RuntimeException('Facade does not implement getFacadeAccessor method.');
}
</code></pre>

<p>Next, we have a protected static method called <code>getFacadeAccessor()</code>. This method is designed to be overridden when extending the Facade class to return a string, the key which the service represented by the facade is bound within the container. By default, it throws an exception if not implemented. This gives a more informative message to those creating custom facades than if the framework were to instead use an abstract method.</p>

<p>Here’s an example of how the method looks when overridden in the <code>DB</code> Facade.</p>

<pre><code>&lt;?php

use Illuminate\Support\Facades\Facade;

class DB extends Facade  
{
    protected static function getFacadeAccessor()
    {
        return 'db';
    }
}
</code></pre>

<p>Since it’s a protected method, any calls from within the abstract class will retrieve the value ‘db’. The above sample is all that’s required to create a new facade. A class that extends the <code>Illuminate\Support\Facades\Facade</code> abstract class, and an overriding <code>getFacadeAccessor()</code> method returning the string value of the container binding for the service it represents.</p>

<p>To see how this all fits together, let’s take a look at the final method of our simplified abstract facade class. Note that I’ve changed this heavily from the real implementation to increase the clarity of the example. However, for the most part, it functions in a similar way.</p>

<pre><code>&lt;?php

public static function __callStatic($method, $args)  
{
    if (!static::$resolvedInstance) {
        $key = static::getFacadeAccessor();
        static::$resolvedInstance = static::$app-&gt;make($key);
    }

    $instance = static::$resolvedInstance;

    return $instance-&gt;$method(...$args);
}
</code></pre>

<p>The <code>__callStatic()</code> method is a PHP magic method which is executed when a static method is called, that does not exist on the class. Its arguments <code>$method</code> and <code>$args</code> will contain the name of the method that was called, and an array of the arguments supplied.</p>

<p>The Laravel Facade intercepts these static method calls to proxy them to the service instance held within the container. First, it must retrieve the service instance from the container  (<code>static::$app</code>) by using the binding retrieved by calling <code>getFacadeAccessor()</code>. The service is then stored in the resolved property to speed up future calls.</p>

<p>Finally, the originally intended method is called on the service instance, passing the original parameter set. Laravel uses the <a href="http://php.net/manual/en/migration56.new-features.php#migration56.new-features.splat">PHP 5.6 splat</a> (...) operator to pass a sequence of parameters from an array. The result of this method is returned, allowing for a value to be used, or additional methods to be chained.</p>

<p>So you see, each static method call on a Facade is actually passed to a service instance inside the container. This means that we can easily swap the contained instance for a mock, to achieve the same functionality as we saw using dependency injection. This makes Facade’s as easily testable as using dependency injection.</p>

<p>Actually, some would say that Facades can be slightly easier to test, because of some helper methods available on the Facade abstract class. There are several methods for swapping the resolved instance for a <a href="https://daylerees.com/laravel-facades/">Mockery</a> mock object, here’s an example.</p>

<pre><code>&lt;?php

DB::shouldReceive('foo')...  
</code></pre>

<p>If you’d rather not use mockery, you can swap the stored instance directly with the <code>swap()</code> method of the Facade. For example:</p>

<pre><code>&lt;?php

DB::swap(new FakeDatabase);

// Call is now made on our 'FakeDatabase' instance.
DB::table();  
</code></pre>

<p>These methods can be extremely powerful!</p>

<p>I hope you’ve gained an understanding of how the Facade classes function, and why they are not static traps to be feared or avoided. If you’d like to read on, the next section contains an advanced consideration for favoring dependency injection over Facade usage.</p>

<h2 id="considerations">Considerations</h2>

<p>There is an argument for favoring dependency-injection over Facade usage that will help to explain why the majority of experienced Laravel developers will use constructor-based contract type-hinting to inject their dependencies.</p>

<p>Type-hinting services within the constructor forms it’s own ‘kind of’ contract. If the constructor requires a cache contract implementation, then it <strong>must</strong> be instantiated with one, and will not function without.</p>

<pre><code>&lt;?php

use Illuminate\Contracts\Cache\Factory as Cache;

class MyController  
{
    protected $cache;

    public function __construct(Cache $cache)
    {
        $this-&gt;cache = $cache;
    }
}
</code></pre>

<p>If we were to use a facade instead, the class could still be instantiated, and if the service behind the facade was not found in the container, then we’d only find out when we first try to make use of it.</p>

<p>Injection through the constructor also gives additional clarity to the dependencies of the class, that is much easier to observe than scanning the class source for Facade usages.</p>

<p>Finally, dependency injection through the constructor makes it easier to test the class <em>without</em> involving the Laravel framework. We could test the class in isolation, without the use of a container, by instantiating our cache instance ourselves, and passing it as a parameter when instantiating the class. Often, tests work best when they are kept simple and isolated. For this reason, the means of separation from the framework’s container may be useful to you.</p>

<p>If you have any questions about Facades (or anything else for that matter!) then please leave a comment below! I’d be happy to help.</p>

<p>Once again, thanks for reading, and if you enjoyed the article then please share it with your friends!</p>]]></content:encoded></item><item><title><![CDATA[Container Baking]]></title><description><![CDATA[Learn how to create a dependency-resolution inversion-of-control container. Just like the one that Laravel uses.]]></description><link>https://daylerees.com/container-baking/</link><guid isPermaLink="false">747b322e-8af7-4e93-8ab2-79c1fb78e9dc</guid><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Wed, 24 Jan 2018 23:17:04 GMT</pubDate><content:encoded><![CDATA[<p>Hi there folks! Thanks for tuning into today’s episode of baking code with Dayle. Today, we’ll be rusting up a fresh batch of IoC container! Mmm, mm. Not just any IoC Container, but the dependency resolution flavor! Super tasty. Here are the ingredients you’ll be needing.</p>

<ul>
<li>An understanding of Dependency Injection.</li>
<li>An understanding of Inversion of Control.</li>
<li>Exposure to the PHP Reflection classes.</li>
</ul>

<p>Oh, some of you don’t have the ingredients? No problem, you can use mine! We’ll look at these techniques and tools as we go along.</p>

<p>Right then, now that I’ve broken the ice, I think we can lose the baking metaphors. What we’re looking to understand and create in this article, is a dependency-resolution-enabled inversion-of-control container. Now those are some pretty complicated terms, but I promise you, they aren’t anywhere near as scary as they first may seem.</p>

<p>This type of container you’ll find in a number of projects. It’s the backbone of the Laravel Framework, containing all the services available to the user.</p>

<p>It would be a shame to have to set-up a new database connection everytime that we use it, supplying the port, host, username, and password, so instead, we bind that service into the container so that we can use it in multiple places. That’s the beauty of the container!</p>

<p>Laravel’s implementation of the automatic dependency resolution (where it can instantiate classes by providing their constructor dependencies automatically) has been one of the more popular implementations in the PHP world, and we’ll aim to replicate that functionality within this article.</p>

<p>Let’s start by putting it together, piece by piece. First, we’ll setup our environment. In the project folder, we create <code>src</code> and <code>tests</code> directories to store the container code, and the tests respectively. We’ll also setup Composer for use in this project, and add PHPUnit as a dependency. Finally, I’ve added a sample <code>phpunit.xml</code> to load the Composer class map, and look in our <code>tests</code> directory for tests.</p>

<p>You’ll find the complete code for this article <a href="https://github.com/daylerees/container-example">on my GitHub account</a>. However, I highly recommend waiting until you’ve finished the article before playing with it.</p>

<p>First, we’ll start with an empty container class. We’ll place it in the <code>src</code> folder. I’ve configured Composer to map classes in this folder to the ‘Example’ namespace.</p>

<pre><code>&lt;?php

namespace Example\Container;

class Container  
{

}
</code></pre>

<p>Beautiful and clean! It’s a shame we’re going to make it messy by adding more code, but alas, that’s how applications are built! You’ll notice that I haven’t started with a test. We’re not actually going to TDD the container, not for any good reason, you could if you wanted to, but to make the example shorter and less “let’s check if this fails first” we’ll simply use our tests to execute the code.</p>

<p>We’ll implement the container feature by feature. The first thing we need to do is make it store and retrieve instances of services. This will actually make it more of a ‘service locator’, but it’s a good start point.</p>

<p>To make it store and retrieve instances, we’ll simply use an internal array to hold them. Here’s the example.</p>

<pre><code>&lt;?php

namespace Example\Container;

class Container  
{
    protected $instances = [];

    public function instance($key, $value)
    {
        $this-&gt;instances[$key] = $value;

        return $this;
    }

    public function make($key)
    {
        if (array_key_exists($key, $this-&gt;instances)) {
            return $this-&gt;instances[$key];
        }

        throw new \Exception('Unable to resolve binding from container.');
    }
}
</code></pre>

<p>Don’t be scared! We’ve got this. First, we create a class property called <code>$instances</code>, it’s a protected property that’s initialized to an empty array. This is where we’re going to store all the instances that we bind within the container.</p>

<p>The <code>instance()</code> public method takes two parameters, the first is the name we’ll use to store the instance, and the second is the instance itself. We place the provided instance in our <code>$instances</code> class property, using the <code>$key</code> as our index. I’ve returned <code>$this</code> simply to make the method chainable. That part’s not so important.</p>

<p>The next function is used to retrieve the instances. First, we check to make sure that the provided <code>$key</code> exists within our instances array, and if it does, we’ll return the instance associated with it. If we can’t find a matching index, then it means we don’t have that instance available, so we’ll throw a meaningful exception. Normally, we’d use a more specific exception, rather than the base ‘Exception’ class, but I’m keeping it simple in this example.</p>

<p>Let’s write some tests to further explain this functionality.</p>

<pre><code>&lt;?php

use Example\Container;  
use PHPUnit\Framework\TestCase;

class ContainerTest extends TestCase  
{
    function test_container_can_be_created()
    {
        $container = new Container;
        $this-&gt;assertInstanceOf('Example\Container', $container);
    }

    function test_instance_can_be_bound_and_resolved_from_the_container()
    {
        $instance = new Dummy;
        $container = new Container;
        $container-&gt;instance(Dummy::class, $instance);
        $this-&gt;assertSame($instance, $container-&gt;make(Dummy::class));
    }

    /**
     * @expectedException Exception
     */
    function test_exception_is_thrown_when_instance_is_not_found()
    {
        $container = new Container;
        $container-&gt;make('FakeClass');
    }
}

class Dummy {}  
</code></pre>

<p>Before we begin looking at the tests, note that we have a dummy class at the bottom of the file, we’ll use instances of this to test our bindings.</p>

<p>In the first test, we simply create a new container instance. You might think that this is an odd one, but it’s one I like to add to any new code. It means that if I’m working on a team, no one will add a constructor parameter to the class without thinking about the consequences of that action. It’s not very important to this example, simply muscle memory.</p>

<p>Next, we have the important test. It’s binding an instance of <code>Dummy</code> inside the container, using the class name <code>Dummy::class</code> as the key. Then, we’re retrieving the value from the container using the <code>make()</code> method and the same key and ensuring that the value we receive is the same instance that we stored (not just equal, but the exact instance that we stored).</p>

<p>Finally, we have a test which attempts to retrieve a binding from the container, without registering anything within it. Essentially, trying to get an instance that it doesn’t have. We assert that we expect an exception.</p>

<p>All three tests pass successfully in this case. We could also add a number of tests around retrieving multiple services, and register different types, but this isn’t an article on testing, so we’ll move along.</p>

<p>What we have now is a service locator. It stores services and retrieves their references on demand. The problem with this implementation is that the instances <strong>MUST</strong> be created at the time of binding. We instantiate the instances of classes, before putting them into the container. This means that their startup routines will be running, and their initial state will be stored. This could waste CPU cycles and memory. This is extremely wasteful if we consider that not all the services will be used in every request.</p>

<p>It would be much better if the services could be created on demand. When they are needed. We can do this without a controller ourselves, but that means exposing more of our codebase to our configuration values to make sure that they are set up right.</p>

<p>Instead, we can leverage Inversion of Control to achieve what we’re looking for. This is the IoC in IoC container. Essentially, we teach the container how to create services for us. So that it will create them when they are requested, and not as they are registered.</p>

<p>In PHP a language feature called a ‘Closure’ that was added in version 5.3 makes this extremely convenient. (Note that it was still possible before 5.3 using a class to register services, but that had more overhead.)</p>

<p>A closure is a function that we can store as a variable, and hand it around our application as needed. Consider the following closure.</p>

<pre><code>&lt;?php

$dummyResolver = function() {
    return new Dummy;
}

$dummy = $dummyResolver();
</code></pre>

<p>In the above example, the instance of <code>Dummy</code> won’t be created until the last line, where the closure is executed. We can use this functionality to add IoC to our container.</p>

<p>Let’s add a new method called <code>bind()</code> to the container, instead of binding instances directly, we’ll store closures in a new class property array called <code>$bindings</code>.</p>

<pre><code>&lt;?php

namespace Example;

class Container  
{
    protected $instances = [];

    protected $bindings = [];

    public function instance($key, $value)
    {
        $this-&gt;instances[$key] = $value;

        return $this;
    }

    public function bind($key, $value)
    {
        $this-&gt;bindings[$key] = $value;

        return $this;
    }

    public function make($key)
    {
        // Hidden for simplicity.
    }
}
</code></pre>

<p>Now we’ve got two methods for storing things in the container. One for storing class instances, and another for storing closures which will be the blueprints for creating new instances. Instances will be held by key within the <code>$instances</code> class property, and closures will be held within <code>$bindings</code> in the same format.</p>

<p>Let’s now update the <code>make()</code> function so that it can retrieve these bindings.</p>

<pre><code>&lt;?php

public function make($key)  
{
    if (array_key_exists($key, $this-&gt;instances)) {
        return $this-&gt;instances[$key];
    }

    if (array_key_exists($key, $this-&gt;bindings)) {
        $resolver = $this-&gt;bindings[$key];
        return $resolver();
    }

    throw new \Exception('Unable to resolve binding from container.');
}
</code></pre>

<p>Now if we try to resolve a dependency that isn’t stored as an instance, it will check to see if there’s a binding for it. If the binding exists, we’ll execute the closure (creating the instance within) and return that to the user.</p>

<p>As it stands, if we were to call the <code>make()</code> method several times, it would run the closure each time and we’d receive a brand new instance each time the closure runs. This is how Laravel’s <code>bind()</code> method works, however, it also has <code>singleton()</code> which is a variant of this, and instead only runs the closure the first time that binding is requested, and then caches it to supply if the instance is requested again in the future.</p>

<p>We can change our code to easily reflect this ‘singleton’ nature. Let’s have a go. Note that Laravel uses two arrays to store both normal bindings and singleton ones. We’re just going to support singleton instead.</p>

<pre><code>&lt;?php

public function make($key)  
{
    if (array_key_exists($key, $this-&gt;instances)) {
        return $this-&gt;instances[$key];
    }

    if (array_key_exists($key, $this-&gt;bindings)) {
        $resolver = $this-&gt;bindings[$key];
        return $this-&gt;instances[$key] = $resolver();
    }

    throw new \Exception('Unable to resolve binding from container.');
}
</code></pre>

<p>It’s a tiny change, but a huge difference! The first time we look in the <code>$bindings</code> array for a service, we store the result in the <code>$instances</code> array using the same key. Because the container always looks for instances first, any subsequent requests to <code>make()</code> for the same service will result in <em>exactly</em> the same service instance being restored. We can prove this using a test.</p>

<pre><code>&lt;?php

function test_singleton_bindings_can_be_resolved()  
{
    $resolver = function() { return new Dummy; };
    $container = new Container;
    $container-&gt;bind(Dummy::class, $resolver);
    $this-&gt;assertInstanceOf('Dummy', $container-&gt;make(Dummy::class));
    $dummy = $container-&gt;make(Dummy::class);
    $this-&gt;assertSame($dummy, $container-&gt;make(Dummy::class));
}
</code></pre>

<p>Here we create a closure that forms a blueprint for creating instances of the <code>Dummy</code> class. We <code>bind()</code> that blueprint into the container using the <code>Dummy::class</code> (results in a string called ‘Dummy’) as the key. First, we assert that the item that we get back from the container is an instance of <code>Dummy</code>, and then we resolve once more, to ensure that both instances are <em>exactly</em> the same.</p>

<p>And with that, we now have an Inversion of Control container. Our container can use closures as blueprints to create and return instances of services for us, it also caches the service, so that it’s only ever created once.</p>

<p>There’s another feature remaining, and that’s the automatic dependency resolution. Let’s use the Laravel container as an example. <br>
If we were to try and resolve the class <code>Foo</code> from the container, it would check for instances and bindings first, but if it doesn’t exist in those collections, it will next look to see if there’s a class available called <code>Foo</code> and return a new instance.</p>

<p>We can extend our <code>make()</code> method to implement this functionality using <code>class_exists()</code>. Let’s try that now.</p>

<pre><code>&lt;?php

public function make($key)  
{
    if (array_key_exists($key, $this-&gt;instances)) {
        return $this-&gt;instances[$key];
    }

    if (array_key_exists($key, $this-&gt;bindings)) {
        $resolver = $this-&gt;bindings[$key];
        return $this-&gt;instances[$key] = $resolver();
    }

    if (class_exists($key)) {
        return new $key;
    }

    throw new \Exception('Unable to resolve binding from container.');
}
</code></pre>

<p>We’ve added a third step to our make method. (Note that this method should probably be broken down using extract-method refactoring, but we’re more interested in the concept than the architecture.)</p>

<p>The third step checks to see if the class exists (within autoload scope) and if it does, it will return a new instance of that class. Let’s use a test to prove this functionality.</p>

<pre><code>&lt;?php

function test_resolve_class_instance_by_name_without_binding()  
{
    $container = new Container;
    $dummy = $container-&gt;make(Dummy::class);
    $this-&gt;assertInstanceOf('Dummy', $dummy);
}
</code></pre>

<p>We create a new container instance, don’t bind anything into it, and then try and <code>make()</code> an instance of <code>Dummy</code> by class name. We use <code>assertInstanceOf()</code> to prove that what we receive is a dummy instance.</p>

<p>Our container can see a class called ‘Dummy’ is available, so instantiates and returns it for us.</p>

<p>That’s dependency resolution covered, but Laravel goes a step further with recursive dependency resolution. Before we can understand this concept, we need to learn about simple and complex classes. Consider the following classes.</p>

<pre><code>&lt;?php

class Foo {}

class Bar {  
    public function __construct(int $value)
    {
        // Do something with $value...
    }
}
</code></pre>

<p>In the above example, I would describe ‘Foo’ as a simple class. It doesn’t require any constructor parameters to be instantiated, so it’s really easy for our container to do it for us.</p>

<p>The second class ‘Bar’ could be described as a complex class. It requires an integer constructor parameter to be instantiated. Sure, our container could take a guess at the integer, maybe throw a 5 in there and hope for the best, but that would be a dangerous action. This class shouldn’t be automatically resolved, and if we try to resolve it with our current container we’ll find that it will fail (missing the constructor parameter).</p>

<p>Next, let’s consider the following classes.</p>

<pre><code>&lt;?php

class Bob {}

class Bill {  
    public function __construct(Bob $bob)
    {
        // Do something with $bob.. probably build something...
    }
}
</code></pre>

<p>Bob is another simple class, bless him. Bill, however, is a little more complex, but fortunately, not too complex. Bill takes an instance of Bob within its constructor. If Bob is a simple class, then why don’t we just create an instance, and then we can create an instance of Bill, right? That’s the philosophy behind the Laravel container’s dependency resolution. In fact, if Laravel can create dependencies, it will satisfy them all the way down the dependency chain, so long as the top-most class is resolved from the container.</p>

<p>For example:</p>

<pre><code>&lt;?php

class Bob {}

class Bill {  
    public function __construct(Bob $bob) { /* ... */ }
}

class Barry {  
    public function __construct(Bill $bill) { /* ... */ }
}
</code></pre>

<p>If you try to resolve Barry from the Laravel container. It will try to create an instance of Bill, but to create Bill, it will first create an instance of Bob. That’s recursive dependency resolution for you.</p>

<p>Right, let’s build this! Things are going to get a little more complicated now. We’re going to start playing with PHP’s reflection classes, and there’s a good chance you might not have used them before. These are a collection of classes that are used to inspect things in PHP at runtime, specifically we’ll be using them to determine the parameters required to instantiate a class.</p>

<p>First, let’s refactor what we have a little because our <code>bind()</code> function would otherwise get pretty big.</p>

<pre><code>&lt;?php

public function make($key)  
{
    if (array_key_exists($key, $this-&gt;instances)) {
        return $this-&gt;instances[$key];
    }

    if (array_key_exists($key, $this-&gt;bindings)) {
        $resolver = $this-&gt;bindings[$key];
        return $this-&gt;instances[$key] = $resolver();
    }

    if ($instance = $this-&gt;autoResolve($key)) {
        return $instance;
    }

    throw new \Exception('Unable to resolve binding from container.');
}

public function autoResolve($key)  
{
    if (class_exists($key)) {
        return new $key;
    }

    return false;
}
</code></pre>

<p>We’ve split the auto-resolution stuff out into its own method. The functionality of the class hasn’t changed at all here, it just means that we can focus on the <code>autoResolve()</code> method and thus the code samples in this section can be a little lighter! Of course, we confirmed that the refactor didn’t effect functionality by running our test suite, didn’t we? Ahhh, the wonderful safety-net of test confidence!</p>

<p>Right, let’s jump straight in with the full implementation.</p>

<pre><code>&lt;?php

public function autoResolve($key)  
{
    if (!class_exists($key)) {
        return false;
    }

    $reflectionClass = new \ReflectionClass($key);

    if (!$reflectionClass-&gt;isInstantiable()) {
        return false;
    }

    if (!$constructor = $reflectionClass-&gt;getConstructor()) {
        return new $key;
    }

    $params = $constructor-&gt;getParameters();

    $args = [];

    try {
        foreach($params as $param) {
            $paramClass = $param-&gt;getClass()-&gt;getName();
            $args[] = $this-&gt;make($paramClass);
        }
    } catch (\Exception $e) {
        throw new \Exception('Unable to resolve complex dependencies.');
    }

    return $reflectionClass-&gt;newInstanceArgs($args);
}
</code></pre>

<p>So if you’re looking at this and thinking “Woop, now he’s lost me.” then don’t worry, we’ll go through it line by line to explain what’s happening.</p>

<pre><code>&lt;?php

if (!class_exists($key)) {  
    return false;
}
</code></pre>

<p>So we’ve done this part before. If the class named in the key doesn’t exist, we definitely can’t create it, so we’ll exit early by returning <code>false</code>.</p>

<pre><code>&lt;?php

$reflectionClass = new \ReflectionClass($key);
</code></pre>

<p>We’re going to use reflection to examine the class that we intend to instantiate. To do this, we’ll create a new <code>ReflectionClass</code> and pass the name of the class we’re trying to instantiate to its constructor. The <code>$reflectionClass</code> instance contains a wealth of methods that will allow us to inspect the class. You’ll find more about the <a href="http://php.net/manual/en/book.reflection.php">reflection classes on the PHP API docs</a>.</p>

<pre><code>&lt;?php

if (!$reflectionClass-&gt;isInstantiable()) {  
    return false;
}
</code></pre>

<p>First we check the <code>isInstantiable()</code> method on the reflection class. If our subject can’t be instantiated, then our container can’t do anything with it, so we’ll exit early.</p>

<pre><code>&lt;?php

if (!$constructor = $reflectionClass-&gt;getConstructor()) {  
    return new $key;
}
</code></pre>

<p>Next, we use the <code>getConstructor()</code> method of the <code>$reflectionClass</code> to determine whether our subject has a <code>__construct()</code> method. If the class exists, is instantiable, but has no constructor, then we can consider it a simple class. We’ll just return a new instance of that class. That’s a nice result!</p>

<p>Of course, if the class does have a constructor, we need to think about the possibility that it might have parameters.</p>

<pre><code>&lt;?php

$params = $constructor-&gt;getParameters();
</code></pre>

<p>This one is nice and simple. Using the <code>getParameters()</code> method, we receive an array of <code>ReflectionParameter</code> instances for any parameters that the constructor might have.</p>

<p>You’ll notice that we’re using this method on the <code>$constructor</code> value, that’s because the <code>getConstructor()</code> method of the reflection class returns an instance of <code>ReflectionMethod</code>. So the chain is something like this:</p>

<p><code>ReflectionClass(classname) -&gt; getConstructor() -&gt; ReflectionMethod -&gt; getParameters() -&gt; ReflectionParameter[]</code></p>

<p>We’ll make use of those parameters, but first, we need a buffer to save our resolved parameters into.</p>

<pre><code>&lt;?php

$args = [];
</code></pre>

<p>That will do nicely. Hopefully, there’s no explanation needed here!</p>

<pre><code>&lt;?php

try {  
    foreach($params as $param) {
        $paramClass = $param-&gt;getClass()-&gt;getName();
        $args[] = $this-&gt;make($paramClass);
    }
} catch (\Exception $e) {
    throw new \Exception('Unable to resolve complex dependencies.');
}
</code></pre>

<p>Here’s a slightly bigger chunk of code. We’re going to wrap it in a try, because if any of the parameters can’t be resolved, then we’re going to fail to instantiate our class. We’ll catch the exception thrown by <code>make()</code> and show something more meaningful.</p>

<p>We’ll loop through the array of <code>ReflectionParameter</code> instances, and deal with one at a time. First, we’ll use the method chain of <code>getClass()-&gt;getName()</code> to retrieve the type hinted class name of the expected parameter in string format. We’ll then use recursion to resolve that parameter from our container by calling <code>$this-&gt;make()</code> on it. Because this a recursive action, the dependency resolution will go as deep as needed to satisfy all dependencies down the chain.</p>

<p>If we resolve the parameter instance, we’ll add it to the <code>$args</code> buffer that we created earlier.</p>

<pre><code>&lt;?php

return $reflectionClass-&gt;newInstanceArgs($args);  
</code></pre>

<p>Once we’ve resolved all the parameters, assuming we experienced no exceptions, we are able to create an instance of the class by passing the array to the <code>newInstanceArgs()</code> method of the reflection class. This gives us a new instance of the service we were trying to resolve.</p>

<p>Let’s prove that it works by adding a quick test to our test suite. We’ll add a number of new stubs to the bottom of our test file.</p>

<pre><code>&lt;?php

class Foo {}  
class Bar { function __construct(Foo $foo) {} }  
class Baz { function __construct(Bar $bar) {} }  
</code></pre>

<p>Here we have a chain of dependencies three levels deep. We’re going to test that we can automatically resolve <code>Baz</code> from the container and that all other dependencies are created for us. Here we go!</p>

<pre><code>&lt;?php

function test_we_can_resolve_dependencies_of_dependencies()  
{
    $container = new Container;
    $baz = $container-&gt;make(Baz::class);
    $this-&gt;assertInstanceOf('Baz', $baz);
}
</code></pre>

<p>By asserting the instance of the resulting value as <code>Baz</code>, we know that the container must have created <code>Bar</code> and <code>Foo</code> as part of the instantiation process.</p>

<p>And there we have it ladies and gents, a fully functional dependency-resolution IoC container. Sure, it’s not as pretty as the one Laravel uses, but that’s got a wealth of increased error handling and quality of life features, however, I think our example serves to show that the automatic-resolution stuff is in fact not ‘magic’, but a clever implementation of the reflection classes.</p>

<p>If you’d like to learn more about dependency injection, or would like to learn about some other topics, just ask a question in the comments! Thanks for reading! </p>]]></content:encoded></item><item><title><![CDATA[Message Queues]]></title><description><![CDATA[An introduction to the concept of background processing for the web using message queues.]]></description><link>https://daylerees.com/message-queues/</link><guid isPermaLink="false">be529237-5152-457f-8f49-8d9eb353fa88</guid><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Mon, 22 Jan 2018 22:22:47 GMT</pubDate><content:encoded><![CDATA[<p>Have you ever had a task that takes forever? Maybe you’ve let the dishes pile up for a little too long. Now that you’re keen to do some cooking, you’ve found that you have no clean pots or plates. You’re blocked from creating tasty dishes until you take care of the washing up.</p>

<p>That’s exactly why message queues exist. Well, I suppose not exactly. Look, let’s have a closer look at the problem with a more realistic scenario. Please note that this post aims to explain queueing as a concept, rather than any specific software solution. Still happy? Okay! Read on.</p>

<p>Consider PHP, a language that has progressed by leaps and bounds in recent years in terms of both flexibility and performance. However, there are some limitations that even the most recent versions of PHP cannot fix.</p>

<p>Let’s consider concurrency. I know, I know, I can hear you gasp from here. PHP isn’t a great language for threading, or for asynchronous code in general, and you’re quite right. I’m actually talking about a different type of concurrency.</p>

<p>Let’s examine how PHP and Nginx work together for a moment.</p>

<p>We’ll simplify things a little, but essentially, when Nginx receives a new request for a PHP file, it will create a new PHP-FPM process that will handle the script, and pass the processed response back to Nginx. The web-server can spawn a number of these PHP-FPM processes in parallel. In fact, if you look at the process list of a web-server serving a popular PHP website, you’ll likely see a number of entries for PHP-FPM.</p>

<p>While Nginx will happily spawn a large number of PHP-FPM processes to handle load, there is a configurable limit. Once that limit has been hit, the web-server won’t serve the content as intended. In fact, Nginx also has a configurable limit of simultaneous connections that it can handle. So there are two opportunities to run out of resources when serving web content.</p>

<p>“But Dayle,” you say, “I didn’t come to your blog to learn about DevOps.” That’s perfectly fine, but the bit that’s really important to grasp is that the web-server cannot serve an infinite number of users at once. This is why PHP applications work best when they do their work quickly and serve the response as soon as possible. Freeing up resources (the fpm pool) for new requests.</p>

<p>For now, let’s imagine that FPM can only handle three requests simultaneously. That’s a rather small number compared to the general configuration, but please, bear with me.</p>

<p>User one visits the site, and our script loads some content from an external host. A third party API, shall we say? The API is slow, and the user watches a loading spinner in the corner of the browser.</p>

<p>While they waiting for their request to finish, that means that there are only 2 processes now available to process requests. If two others were to hit the same endpoint, the web-server wouldn’t be able to handle any further requests. That’s a big problem! We don’t want angry users.</p>

<p>In situations such as these, ones where a process may take a long time to complete, we can consider using a queue. However, before we do so, we must ensure that our current request need not send an immediate response.</p>

<p>For example, let’s say we click a button on a website, and it should send an email. Who knows how long it will take to send the email, and we don’t really know when it will be received. So why don’t we queue it instead?</p>

<p>The flow will go like this:</p>

<ul>
<li><strong>User</strong>: Clicks the button.</li>
<li><strong>App</strong>: Queues an email to be sent. Sends a response immediately.</li>
<li><strong>User</strong>: See’s “Thanks, your email has been sent.”</li>
</ul>

<p>Because we queue the item (a fast process) rather than send the email directly, the user isn’t made to wait for confirmation. The page reloads quickly.</p>

<p>So let's think about queueing for the moment? Essentially, we’re storing some work to act upon later. It’s performing an action with some data. That sounds a lot like a function to me, don’t you agree? A function has a name and some parameters. So that’s what our queued message will look like. Here’s an example:</p>

<pre><code>{
    "name": "email.send",
    "data": {
        "user": 123,
        "email": "button_push"
    }
}
</code></pre>

<p>The message above has a name, or type ‘email.send’ and a data payload containing the ID of the user to send the email to, and which email to send.</p>

<p>We could have added subject line, entire email content and much more, but that wouldn't be ideal. Queued messages work best with the minimal data set required to represent the work to be done.</p>

<p>For example, we can use the parameters above to retrieve a user from the database by ID, and then we will have their email address. We could also easily create a system to locate and load the email template, content, and subject line from the email type.</p>

<p>Once we have our queue message, we can place it on our queue. You can think of a queue as a stack. At first, the stack will contain no items.</p>

<ul>
<li><em>(Empty)</em></li>
</ul>

<p>We can place as many items on the queue as we like, here we’ve added a few send email messages to the queue. I’ll leave the JSON out for this example. Format doesn’t really matter, it’s the data that’s important.</p>

<ul>
<li><strong>Send Email</strong>: user:<em>54</em> email:<em>welcome</em></li>
<li><strong>Send Email</strong>: user:<em>67</em> email:<em>welcome</em></li>
<li><strong>Send Email</strong>: user:<em>142</em> email:<em>welcome</em></li>
<li><strong>Send Email</strong>: user:<em>54</em> email:<em>password_reset</em></li>
</ul>

<p>So this queue, where is it stored? Good question. I mean, those just look like records to me, don’t you agree? I suppose we could use the database? Sure, why not! We’ll insert each new message into a database table containing a field for the message name, and another for the message parameters. That’s simple stuff, isn’t it?</p>

<p>And now we’re done! Oh wait, I must be mistaken. Now we’re just throwing messages at the database, but we’re no closer to sending our emails. They’ll just sit there forever, stacking and stacking until we fill the hard disk of our database server!</p>

<p>What we need next, is something called a ‘consumer’ or ‘worker’. It’s a special application that runs independently from your website, and churns through the queue, tackling each message one by one. Here’s how it might look in some basic pseudo code.</p>

<pre><code>while (true) {  
    if (message = queue.getMessage()) {
        // Get user from database.
        // Fetch template and render it.
        // Send email using SMTP.
        message.delete();
    }
}
</code></pre>

<blockquote>
  <p>Hah! Stupid Dayle, can’t you see that you’ve created an endless loop! That’s a rookie coding mistake!</p>
</blockquote>

<p>You’re absolutely right! That is an endless loop, and it’s exactly what we want. You see, the consumer will always be running, checking the queue (polling) for new messages to process. Queue consumers are normally daemonized, a process that runs endlessly. Even once it has emptied the queue of messages, and all emails have been sent, it will sit there eagerly asking the queue for more tasks to complete.</p>

<p>You could set the consumer to handle events of multiple names in different ways. For example, a consumer might know how to send emails, deliver authentication text messages, or capture monthly subscriptions. It might be able to handle all of the above events. It’s really up to you.</p>

<p>What’s important to remember, is you can’t be sure <em>when</em> a message will be processed. You could make an assumption based on the length of the queue, but sometimes it’s hard to say how long jobs will take to be processed. That means that queues are best for non-urgent tasks that ‘will be done as soon as possible, but perhaps not right this second’.</p>

<p>Let’s consider the traits of an action that’s ideal to be queued, once again.</p>

<ul>
<li>May be resource intensive or long running.</li>
<li>Does not need to provide resulting data immediately.</li>
<li>Does not need a predictable processing time.</li>
</ul>

<p>Normally, queues are ideal for background business processes and communications tasks but can be suited to more. Here are a few things that I’ve used queues for.</p>

<ul>
<li>Sending emails or text messages.</li>
<li>Logging content to one/many places.</li>
<li>Taking payments.</li>
<li>Generating (warming) cache content.</li>
<li>Updating the search index for some content.</li>
</ul>

<p>In this example, we’ve used a database table to store our queue because it’s a data storage method that’s very familiar to most developers, however, there are a number of software solutions that are much more effective.</p>

<ul>
<li><a href="https://aws.amazon.com/sqs/">Amazon SQS</a></li>
<li><a href="https://www.rabbitmq.com/">RabbitMQ</a></li>
<li><a href="http://kr.github.io/beanstalkd/">Beanstalkd</a></li>
<li><a href="http://www.iron.io/mq">IronMQ</a></li>
<li><em>Obligatory ‘and many more!’</em></li>
</ul>

<p>Not only will these solutions likely be faster than using the database, but they have a feature set tailored to queuing jobs. For example, supporting locking (ensure a job doesn’t get processed twice) fanout (deliver a message to multiple queues) and more!</p>

<p>That’s all there is to queues as a concept, so feel free to escape at this point. However, I have a few bonus topics for those who are naturally curious.</p>

<h2 id="performanceparallelism">Performance &amp; Parallelism</h2>

<p>If you find yourself in the position where the number of messages in your queue are rising faster than your consumers are processing them, then don’t panic! It means you're busy, maybe collecting loads of money. It’s a good problem to have!</p>

<p>But you’re probably looking for a solution, right? Well, it’s actually a really simple one! Simply run more consumers. If you run more consumers in parallel, you’ll be able to double..triple..etc the processing time of your jobs. Run as many parallel consumer instances as you require to keep the message numbers down.</p>

<p>Companies with advanced infrastructure will use DevOps techniques that scale the number of consumers dynamically depending on the number of messages in the queue. This can be an extremely cost-effective way of managing queues.</p>

<p>You can also consider splitting your consumers by type. Arranging so that some consumers handle different jobs to others. Many developers opt for having high/low urgency queues so that only urgent tasks will be placed on the high queue, keeping the number of messages (and thus, response time) low.</p>

<h2 id="usefulframeworks">Useful Frameworks</h2>

<p>Many frameworks come with a solution for queueing, and you’ll also find a wide number of open-source consumers online available for the different queuing mechanisms.</p>

<p>Most frameworks treat queuing in a similar manner to routing. Instead of using the URL to route requests, we’ll use the message ‘name’ or ‘key’ to select the appropriate code to handle the job.</p>

<p>Why not take a look at how <a href="https://laravel.com/docs/5.5/queues">Laravel handles queued tasks</a>?</p>

<h2 id="gotchas">Gotchas</h2>

<p>A lot of the gotchas relating to queues are related to asynchronous programming in general. It’s impossible to judge the amount of time between a message being placed on the queue, and it being processed. A lot can happen in the interval.</p>

<p>Consider the following situation. We place a message on the queue to send an email to user 32, embedding their email ‘foo@example.com’ within the message. Between the message being placed on the queue, and it being processed by the consumer, the user may have changed their email address on the website. However, the queued message will still contain the old email address, and the email will be sent to the wrong destination.</p>

<p>For this reason, it’s best to only store stable information on the queue, in the above example, the primary key (id) field of the user table might be a better choice. We can use that to retrieve the email address from within the consumer, and it’s very unlikely that a user is able to change their id.</p>

<p>Depending on the queueing solution that you end up with, you might find race conditions within your consumers. For example, two consumers may take the same job from the queue at the same time, if both were to process it, it might cause odd problems. An email might be sent twice, for example.</p>

<p>To avoid these issues, it’s best to implement a locking mechanism, or simply to use a trusted message queue solution that will no doubt handle this for you.</p>

<hr>

<p>Well, I hope you’ve learned something new from the article! If there’s anything you find confusing, please don’t be afraid to ask questions in the comment. There’s no such thing as a stupid question!</p>

<p>Do you have another programming topic that you'd like explained in my own special way? Feel free to make a request in the comments!</p>

<p>Have a wonderful day!</p>]]></content:encoded></item><item><title><![CDATA[Rainglow Project]]></title><description><![CDATA[A look back at the progression of the Rainglow project, and what the future holds for users of the color theme collection.]]></description><link>https://daylerees.com/rainglow-project/</link><guid isPermaLink="false">77b84227-bdd8-4ced-aa9f-582005a77a5b</guid><category><![CDATA[Rainglow]]></category><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Wed, 17 Jan 2018 23:55:25 GMT</pubDate><content:encoded><![CDATA[<p>I thought it might be fun to reflect on the past few months of Rainglow. For those visiting this page and wondering what I'm talking about, Rainglow is a collection of over 300 themes for a number of different editors and software. I've designed every single theme in the collection, and painstakingly developed a great level of support for the tools available.</p>

<p><img src="https://daylerees.com/content/images/2018/01/bold.png" alt="vscode"></p>

<p>Rainglow wasn't the first iteration of this project. Initially, it was simply called 'Dayle Rees Colour Schemes' and was released for Sublime Text, and then widened to additional editors.</p>

<p>The V1 of the color themes <a href="https://packagecontrol.io/packages/Dayle%20Rees%20Color%20Schemes">received over 120k downloads on Sublime Text alone</a> over the space of 3 or 4 years. The <a href="https://github.com/daylerees/colour-schemes">original repository</a> also has almost 9000 stars on Github. This means that my color schemes project was both the most popular project I've ever created and the least lucrative! There's certainly no way to monetize color themes that wouldn't have a negative effect on the overall impact of the collection. Therefore, we find other means of motivation, such as the drive to get as many developers using the project as possible. A personal highlight of mine from the first version was seeing 'Earthsong' and 'Peacock' show up on the HBO Silicon Valley TV show. Look ma, I'm famous!</p>

<p><img src="https://daylerees.com/content/images/2018/01/rainbow.png" alt="vscode2"></p>

<p>So why start again? There were, in fact, a few reasons. The first was simply that other work got the better of me, a lack of a comfortable working environment certainly had its toll also. </p>

<p>I also found that the tools I used to maintain the first version of the project weren't well suited to the size that the project had become. It was an open-source form of tech debt that got the better of me!</p>

<p>When I found myself in a better place, where I could focus again on side projects, I decided to pick one that was really important to me and focus entirely on that for a while. I chose color themes because they are a big part of a developers day. If you're staring at walls of text all day for weeks at a time, then you should at least be able to pick from more than 8 stock color themes and find new ways of finding joy in the work that you do.</p>

<p>I gave a great deal of thought to the problems I was facing with the original themes package, and then rebuilt all of the tooling that I needed. It's now much more robust, and as you can see from the size of the project, it's far more simple to maintain.</p>

<p>Ultimately, it's powered by a number of NodeJS applications and a little bit of docker for some of the automation. The theme preview site was built with React.</p>

<p>I decided upon Rainglow as a brand because I felt it was more of a colorful term than my own name. Of course, a brand needs a fancy logo! So putting my amateur design skills to work I invented the 'upside-down-rainbow'. The 'Rainglow'. Initially, the concept was for it to symbolize a reflection of a Rainbow that you might see in the water, but I think the more "solid" version that you see now works a bit better. There was no other reason for making it upside down. No hidden meaning, so don't stress yourself trying to figure it out! If it were the right way up, it would just be a Rainbow and not a unique brand.</p>

<p><img src="https://daylerees.com/content/images/2018/01/header.png" alt=""></p>

<p>With the tooling and branding in place, I began making themes. First starting with what I knew to be some of the most popular editors in the web development space. VS Code, Sublime Text, Atom and the JetBrains IDEs.</p>

<p>It didn't take too long at all to theme VSCode, and as part of that journey (mostly the testing process), it quickly became my favorite text editor. The UI theming is a nice touch, and I think it's one of the best applications to get a real "feel" for the themes in. Sublime and Atom I had themed before and weren't too difficult to update to match the quality of VS Code, but sadly without as nice a dynamic theme.</p>

<p>Finally, of the golden four, we had JetBrains, which was my least favorite attempt at theming in the previous iteration. The theming system hasn't really improved since then, but I did start the process from the ground up, instead of re-using the old themes that I had from the V1 of color themes. As a result, I think the themes look a lot better than they used to. Due to changes in the rendering engine, it's simply not possible to get them to render exactly like they do in VS Code, so instead, I went fully custom and wrote them in such a way that the 'personality' of the theme was still apparent in the JetBrains IDE's. There are one or two bugs that I'm aware of, but overall I'm pleased with the result.</p>

<p>After the golden four, I took a break to write some new themes. The first I had created in a while, and I'm really pleased with some of the new additions. A few users have claimed that the number has caused the sensation of 'analysis paralysis' but personally, I think a wider range of themes means that you're more likely to find the one that's perfect for you!</p>

<p>Some of the newer themes that I'm very pleased with are Newton, Glance, and Warlock Contrast. I've been using these a lot. I absolutely love Newton in VS Code.</p>

<p><img src="https://daylerees.com/content/images/2018/01/Screen-Shot-on-2018-01-17-at-11_49_02-pm.png" alt=""></p>

<p>After adding more themes, I decided that the light themes were very few in number, and it didn't seem fair to ignore those who prefer the lighter editors. As a result of this line of thinking, I added light variations of every theme in the collection, followed shortly after by contrast versions. The 320+ total theme count is actually a combination of these, in terms of total unique themes, we're looking more at around the hundred mark, which I'm still very satisfied with!</p>

<p>Following the theme additions, I continued to theme lots of new software in a coffee-fueled rampage, and somewhere along the way did a little research required to create a colorblind theme for those who are unfortunately unable to enjoy the full spectrum of the Rainglow. Huge thanks to Jesse for the help on that one!</p>

<p>Later, I built <a href="https://rainglow.io">a mobile preview site</a>, and then <a href="https://rainglow.io/preview">a React-based dynamic theme preview site</a>, which I'm very pleased with, and I hope you are too!</p>

<p><img src="https://daylerees.com/content/images/2018/01/Screen-Shot-on-2018-01-17-at-11_50_12-pm.png" alt=""></p>

<p>Aside from the supported software listed on the website, there's a work in progress <a href="https://github.com/rainglow/syntax/tree/master/themes">repository of web-syntax themes</a> for highlighters and websites that support theming. As mentioned, these are extremely experimental, but feel free to take a peek!</p>

<p>Finally, I launched <a href="https://teespring.com/stores/rainglow">a line of T shirts</a> to allow people to financially support the project, but also to actually wear their favorite color scheme, which is a cool idea that I haven't seen executed in the past. Sadly, I don't think the T-Shirt store has been very popular, but I am very grateful to those who have purchased the T-shirts and are wearing their colors with pride! Thank you all!</p>

<p><img src="https://daylerees.com/content/images/2018/01/4455e8dc31e9b02.png" alt=""></p>

<p>So what does the future hold for Rainglow? Well, I'm certainly pleased with the progress that has been made, and I imagine that the project will slow a little in terms of additional editor editions (we're running out of them!) but there are a few things still on my list, plenty of ideas up my sleeve, and naturally, I will endeavor to continually improve the quality of the existing theme packages over time. I'd definitely love to add more JS in-page syntax highlighter support, so expect some time spent there.</p>

<p>I'd absolutely love to get the themes in the hands of more users. I estimate that Rainglow is currently used by around 30,000 developers, which is a fantastic achievement for a project that is a little over a month old. However, I've somewhat exhausted my networks and would love to reach out further with the themes so more developers can enjoy them.</p>

<p>I'd be incredibly grateful for your support in this effort. Please share the themes wherever possible. Share them on product sites, write blog posts about them, link to them from editor forums. All of these efforts will help bring more users to Rainglow, and to keep the project fresh. Together, we can give the development world a colorful coding experience!</p>

<p>Finally, I'd like to say a huge thank you to the development community who use the themes and have been incredibly polite, appreciative, and entirely awesome to me while I've been working on this project. You've all been fantastic, and it's been a pleasure sharing Rainglow with you.</p>

<p>Have a bright, colorful, and slightly upside down day!</p>

<p><img src="https://daylerees.com/content/images/2018/01/big-rainbow-.png" alt=""></p>]]></content:encoded></item><item><title><![CDATA[First Steps into React for Javascript]]></title><description><![CDATA[Learn the basic concepts behind the React Javascript templating library.]]></description><link>https://daylerees.com/first-steps-into-react/</link><guid isPermaLink="false">7653df56-1587-48e5-b211-08d229d2f755</guid><category><![CDATA[React]]></category><category><![CDATA[Javascript]]></category><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Sun, 14 Jan 2018 03:02:57 GMT</pubDate><content:encoded><![CDATA[<p>In this article, we're going to take a quick look at the <a href="https://reactjs.org/">React templating library</a> from Facebook. It's an extremely popular project, and I've been using it for some of my side projects. In fact, React powers the <a href="https://rainglow.io/preview">preview app</a> for my <a href="https://rainglow.io">Rainglow project</a>!</p>

<p>Don't worry PHP guys, I haven't given up on PHP, I actually use a range of different languages. Use the tool most suitable for the problem you're facing!</p>

<p>We're not going too deep into React in this article. Instead, we'll take a look at a few React concepts, so that you'll know what those fancy-pants Javascript developers are talking about. Let's get going!</p>

<h2 id="jsx">JSX</h2>

<p>The first thing that's going to strike your attention if you look at React code, is that some HTML has snuck into the Javascript. Don't worry, it has permission to be there! Just take a look at this example.</p>

<pre><code>someJsx =&gt; {&lt;div&gt;Hi there!&lt;/div&gt;}  
</code></pre>

<p>You see, we're not actually writing Javascript, we're writing JSX. It's very similar to Javascript except that you can store HTML in variables, and return HTML from functions.</p>

<p>You can see that my syntax-highlighter has also been shocked at the HTML present in the Javascript source. Sorry about that, I'll see if I can update it to support JSX later!</p>

<p>JSX takes some getting used to at first, and you'd be among others if at first, you look upon it with distaste. However, after a while, it will grow on you. Trust me.</p>

<p>JSX is a format that is transpiled to Javascript. That means that there's a build process that turns JSX files into native Javascript files so that they can run in the browser.</p>

<h2 id="components">Components</h2>

<p>In the React world, we like to break things down into modular components. For example, if we were writing an email client, we might have one component for the email list, one for an item in that list, one for the preview pane, one for the toolbar, etc, etc.</p>

<p>Keeping things modular makes them easy to understand, extremely re-usable, and simple to test.</p>

<p>Here's an example of a React component.</p>

<pre><code>import React, { Component } from 'react';

class Hello extends Component {

    render() {
        return &lt;div&gt;I am a component!&lt;/div&gt;
    }

}
</code></pre>

<p>This component would simply render a <code>&lt;div&gt;</code> tag with some text inside. You'll notice that the imported dependency <code>React</code> isn't used! Well, actually it is! It's used when the code is transpiled to native Javascript, and so it's a requirement of any JSX file.</p>

<p>You can use other components inside React components. Here's an example.</p>

<pre><code>import React, { Component } from 'react';

import Hello from './Hello';

class Welcome extends Component {

    render() {
        return &lt;div&gt;
            &lt;Hello /&gt;
        &lt;/div&gt;
    }

}
</code></pre>

<p>Here we've nested our <code>Hello</code> component inside the <code>Welcome</code> component. This way, we can build hierarchies of components. This is important because all react applications start with a top-level component, and then break down into smaller components.</p>

<h2 id="props">Props</h2>

<p>Props are component properties. You can pass them into your components when using them. Let's change our <code>Hello</code> component to use a prop.</p>

<pre><code>import React, { Component } from 'react';

class Hello extends Component {

    render() {
        return &lt;div&gt;Hello there {this.props.name}!&lt;/div&gt;
    }

}
</code></pre>

<p>Here we're using a prop called <code>name</code> that we access from <code>this.props</code>. We can use <code>{</code> braces <code>}</code> to output Javascript statements within the template portions of our JSX code.</p>

<p>Now let's alter the <code>Welcome</code> component to pass in a <code>name</code> prop.</p>

<pre><code>import React, { Component } from 'react';

import Hello from './Hello';

class Welcome extends Component {

    render() {
        const myName = 'Dayle';
        return &lt;div&gt;
            &lt;Hello name={myName} /&gt;
        &lt;/div&gt;
    }

}
</code></pre>

<p>We pass props into React components in a similar fashion to how you specify attributes on HTML elements. Here we're passing the <code>myName</code> constant into the component as the <code>name</code> prop.</p>

<p>Our <code>Welcome</code> component will now greet by name! Of course, we could pass any name into the component, making our <code>Hello</code> component re-usable.</p>

<h2 id="state">State</h2>

<p>React components can have state. They use this state to store information that's valuable to them. Let's take a look at an example.</p>

<pre><code>import React, { Component } from 'react';

class Hello extends Component {

    setName() {
        this.setState({name: 'Dayle'});
    }

    render() {
        return &lt;div&gt;
            &lt;p&gt;Hello there {this.state.name}!&lt;/p&gt;
            &lt;button onClick={this.setName.bind(this)}&gt;Set name!&lt;/button&gt;
        &lt;/div&gt;
    }

}
</code></pre>

<p>In this example we've added a button with an <code>onClick</code> event that calls a <code>setName()</code> method on that component. Don't worry too much about the <code>bind()</code> part, that's just a way of changing the scope of the function, and is a handy little Javascript feature.</p>

<p>Initially, when the component renders it will show 'Hello there !' without a name, this is because <code>this.state.name</code> is undefined. If we click the button, our code will call <code>this.setState()</code> to update the state with a name, and the component will re-render to show 'Hello there Dayle!', updating in real time.</p>

<p>Why do we need to use <code>setState()</code> instead of setting <code>this.state</code> directly? Well, React observes the state object, and using the <code>setState()</code> method triggers all the observers, to let React (cleverly) decide which parts of the interface to re-render. It's <em>extremely</em> efficient at doing this! I'm not going to explain why, because that would over-complicate this introduction to the library!</p>

<p>The object literal that you hand to <code>setState()</code> will be "merged" with the state object, overwriting existing keys and values.</p>

<p>What's more useful, is that if the state is passed down the chain into nested components, React is smart, and will re-render the parts of these components that need to change too!</p>

<h2 id="summary">Summary</h2>

<p>What's interesting, is that's basically it for React. Sure, there are a bunch of other features, but what you have here is enough to build a dynamic application for the web. There are plenty of other libraries that you can bring in to do lots of fancy things! Here are some of my favourites.</p>

<ul>
<li><a href="https://redux.js.org">Redux</a></li>
<li><a href="https://www.npmjs.com/package/redux-thunk">Redux-Thunk</a></li>
<li><a href="https://www.styled-components.com/">Styled Components</a></li>
<li><a href="https://www.npmjs.com/package/axios">Axios</a></li>
</ul>

<p>So you see, React isn't all that complex. Unfortunately, as for lots of Javascript libraries, it's the tooling and build processes that sit around React that complicate matters. They aren't entirely welcoming to the beginner Javascript developer.</p>

<p>For that reason, if you'd like to play with React, I'd recommend using <code>create-react-app</code>.</p>

<p>Use NPM or yarn to install the library.</p>

<pre><code>yarn global add create-react-app  
</code></pre>

<p>Now use the script to create a directory containing a fully bootstrapped React application to use as a base for your project.</p>

<pre><code>create-react-app my-project  
cd my-project  
yarn start  
</code></pre>

<p>This will open your project in a web browser. Go ahead and edit <code>src/App.js</code> to see what happens. You'll find that you have hot-reloading, and so your changes to the react project will trigger instantly. It's also got a bunch of useful debugging options. I highly recommend it!</p>

<p>Enjoy playing with React! Let me know if you'd like to see more Javascript or React content.</p>

<hr>

<p>If you found this article useful, then please leave some feedback. Also, I'm currently working really hard on a side project, it's called <a href="https://rainglow.io">Rainglow</a> and it's a collection of hundreds of syntax themes for loads of software! If you can spare a moment, please share it with your friends! That would be awesome. :)</p>

<p>If you'd like to learn about PHP or Laravel, then there are a <a href="https://daylerees.com/books/">bunch of books that I've written on those topics</a>.</p>]]></content:encoded></item><item><title><![CDATA[PHP Interfaces Explained]]></title><description><![CDATA[Learn how to use interfaces effectively in the PHP programming language.]]></description><link>https://daylerees.com/php-interfaces-explained/</link><guid isPermaLink="false">0ad2697e-eb48-4e72-93bc-b6b0225327f8</guid><category><![CDATA[PHP]]></category><category><![CDATA[interfaces]]></category><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Sun, 14 Jan 2018 01:35:53 GMT</pubDate><content:encoded><![CDATA[<p>A few years ago I wrote an article about PHP namespaces; a feature that seemed to mystify the beginner to mid-level PHP developer. Next up, we have interfaces. These are something that I see are misused all the time.</p>

<p>It's such a shame because interfaces are my absolute favourite feature of OO languages! Unfortunately, I often see developers use interfaces poorly; littering their code with them without purpose to try and demonstrate a knowledge of OO design. </p>

<p>Well, this article will show you some practical use for interfaces, so that you can call them out!</p>

<h2 id="howtouseinterfaces">How to use interfaces.</h2>

<p>First, let's take a look at an example interface.</p>

<pre><code>&lt;?php

interface Human  
{

}
</code></pre>

<p>Here we have an entirely empty interface. Interestingly, an empty interface is not without purpose. We can make something great happen from this.</p>

<p>Let's make a few classes that implement this interface.</p>

<pre><code>&lt;?php

class Dayle implements Human  
{

}

class Taylor implements Human  
{

}

class Elon implements Human  
{

}
</code></pre>

<p>The classes that implement our interface now share a common identity. This is useful because we can use <code>instanceof</code> to confirm that identity, for example:</p>

<pre><code>&lt;?php

$elon = new Elon;

if ($elon instanceof Human) {  
    echo 'Well that was a surprise!';
}
</code></pre>

<p>Here, we use <code>instanceof</code> to confirm that the <code>Elon</code> class implements the <code>Human</code> interface. This way we can separate our classes from those that don't implement the interface and deal with them in a different manner.</p>

<p>Of course, why check the class ourselves when we can let type-hinting do the hard work for us? If we're passing a class instance into a function, then we can type-hint the interface directly. Here's an example.</p>

<pre><code>&lt;?php

function feedHuman(Human $human)  
{
    // Feed the $human.
}
</code></pre>

<p>By type-hinting the interface in the function parameter list, we can be sure that any instance passed to this function is an implementation of the <code>Human</code> interface. We don't need to check it ourselves.</p>

<p>If we try to pass any other value into the function, such as an integer, a string or a class instance that doesn't implement the interface, then we'll receive an angry error message.</p>

<pre><code>Fatal error: Uncaught TypeError: Argument 1 passed to feedHuman() must implement interface Human, integer given...  
</code></pre>

<p>This is really useful, now we know that we can type hint interfaces to ensure that we know exactly what type of instance we're working with. We know exactly what we're getting.</p>

<p>But wait, why does it matter that our parameter is a Human? Well right now, there's no reason. We have confirmed the identity, but that identity isn't linked to any functional signatures.</p>

<p>If you've been taught interfaces before, then you've heard that interfaces can define signatures for methods. Here's an example.</p>

<pre><code>&lt;?php

interface Human  
{
    public function eat($food);
}
</code></pre>

<p>Here we've defined a method signature. You'll notice there's no body to the method, we've only defined the method name, visibility, and the parameters it takes.</p>

<p>We don't need to write the body because what we're doing is creating a contract. Here's what the above code is saying:</p>

<blockquote>
  <p>If you make a class implement <code>Human</code>, then it <strong>MUST</strong> have a public <code>eat()</code> method that accepts a <code>$food</code> parameter.</p>
</blockquote>

<p>If you were to make a class that implements the interface but doesn't satisfy the method, for example:</p>

<pre><code>&lt;?php

class Dayle implements Human  
{

}
</code></pre>

<p>Then at runtime, you'll receive the following error. Or if you use a fancy IDE, it might let you know before you run your code!</p>

<pre><code>PHP Fatal error:  Class Dayle contains 1 abstract method and must, therefore, be declared abstract or implement the remaining methods  
</code></pre>

<p>An abstract method is what we call a method without a body. It's what you normally find in interfaces. What the error is saying is:</p>

<blockquote>
  <p>Look, you either need to implement the <code>eat()</code> method in your <code>Dayle</code> class, or you need to make <code>Dayle</code> an abstract class.</p>
</blockquote>

<p>Adding the <code>eat()</code> method to the <code>Dayle</code> class as it appears in the interface (but with a functional body), would satisfy the interface's contract, and remove this error.</p>

<p>Or, we could make the <code>Dayle</code> class abstract, like this:</p>

<pre><code>&lt;?php

abstract class Dayle implements Human  
{

}
</code></pre>

<p>This means that the <code>Dayle</code> class can't be instantiated with the <code>new</code> keyword. Instead, it's a class that is designed to be extended by another class. Like this:</p>

<pre><code>&lt;?php

class BetterDayle extends Dayle implements Human  
{

}
</code></pre>

<p>What we've done, is shifted the responsibility of satisfying that <code>eat()</code> method down a level. Now, the <code>BetterDayle</code> class needs to implement the <code>eat()</code> method or be declared abstract. Either of those techniques will ensure that we don't get that annoying fatal error!</p>

<p>Here's an example of a class that satisfies the contract of our interface.</p>

<pre><code>&lt;?php

class Dayle implements Human  
{
    public function eat($food)
    {
        echo "Mmm, I love {$food}!";
    }
}
</code></pre>

<p>So, now we know that any instance of a class that has our <code>Human</code> interface implemented, or is implemented somewhere in the class inheritance chain (extending), will have a public <code>eat()</code> function.</p>

<p>This means that we can write functions and methods that look like this:</p>

<pre><code>&lt;?php

function feedHuman(Human $human)  
{
    $human-&gt;eat('pizza');
}

feedHuman($dayle); // Mmm, I love pizza!  
</code></pre>

<p>If we hadn't type-hinted the interface, then another developer might have passed a class instance that didn't have an <code>eat()</code> method or even another type like integer or string into the function, and it would have errored when the <code>eat()</code> function couldn't be found on the property.</p>

<p>What we've done is protected our code. We have ensured that any class instance passed to our function has an <code>eat()</code> method. We don't have to check it ourselves, it just <em>has</em> to have that method. Pretty neat, right?</p>

<p>This kind of code is really neat when creating applications that offer custom functionality. Let's take a look at a more practical example, shall we?</p>

<p>Let's imagine that we're writing a PHP application that makes use of a cache. We could write a cache class that looks like this.</p>

<pre><code>&lt;?php

class RedisCache  
{
    public function write(string $key, $value)
    {
        // Code to write the data to Redis...
    }

    public function read(string $key)
    {
        // Code to read the cached data from Redis...
    }
}
</code></pre>

<p>This is quite a common format for caching. We've created a class with two methods. One for writing key-value cache data to <a href="https://redis.io/">Redis</a> (an in-memory key-value storage software) and another for reading data back from Redis by key.</p>

<p>I've omitted the code for actually writing and reading from Redis because it isn't really important for this article. Just imagine that it's there!</p>

<p>This code should function fine, but it's not ideal. Can you tell why? What if the Redis project dies? (I really hope not!) What if we decide to switch to database caching? What if our application is an open source project that's designed to be used by others, do we want to restrict them to using Redis? After all, there are a thousand and one other platforms that can store key-value data, isn't there?</p>

<p>Interfaces to the rescue! Let's use interfaces to future-proof this code, or to allow others to use their own cache mechanisms. First, we're going to need to write the interface. Often, I'll begin by writing the interface first, if I know what the implementations are going to need to do.</p>

<p>We know that caches need to read and write data, and we know that they use keys to identify the cached content. Right then, let's get writing.</p>

<pre><code>&lt;?php

interface Cache  
{
    public function write(string $key, $value): void;

    public function read(string $key);
}
</code></pre>

<p>So we've got our two methods for reading and writing, with the correct type-hinted parameters but <em>no body</em>. That bit is important. We never add a body to an interface. We've type-hinted <code>void</code> as the return type of the write method. It's a PHP 7.1 feature that means the method shouldn't return anything.</p>

<p>Now that we've created an interface, we should type-hint that in the functions or constructors of classes that make use of the cache. Here's an example:</p>

<pre><code>&lt;?php

class Articles  
{
    private $cache;

    public function __construct(Cache $cache)
    {
        $this-&gt;cache = $cache;
    }

    public function fetch()
    {
        if ($articles = $this-&gt;cache-&gt;read('articles')) {
            return $articles;
        }

        // Fetch from original non-cached data store and return.
    }
}
</code></pre>

<p>Here we've got a class for fetching articles. By type-hinting the Cache in the constructor, we ensure that you can only instantiate the <code>Articles</code> class by providing a class instance that implements the <code>Cache</code> interface, and the two methods that are required. This means that we can make use of <code>read()</code> and <code>write()</code> reliably.</p>

<p>What we've actually done here is 'injected' a cache implementation into the class, and set it as a private property of that class instance. This is known as 'dependency injection'. You might have heard of that term thrown around before. It's a great way of making clean, extensible software.</p>

<p>You see, if we'd done something like <code>$this-&gt;cache = new RedisCache;</code> in the constructor, then the only way to replace the cache with another type would be to extend the class, and override the constructor and instantiate our new Cache. That would mean creating another class and would be much messier than simply passing in the cache instance that we want to use.</p>

<p>Anyway, before we get distracted, you'll notice that the <code>fetch()</code> method makes use of our 'injected' cache and attempts to read a list of articles from the cache. If they can't be found, it will fall back to the original data-store. I've hidden that code since it's not important here.</p>

<p>Right, let's create two implementations of our <code>Cache</code> interface.</p>

<pre><code>&lt;?php

class RedisCache implements Cache  
{
    public function write(string $key, $value): void
    {
        // Write cache data to Redis.
    }

    public function read(string $key)
    {
        // Read cache data from Redis.
    }
}

class MongoCache implements Cache  
{
    public function write(string $key, $value): void
    {
        // Write cache data to MongoDB.
    }

    public function read(string $key)
    {
        // Read cache data from MongoDB.
    }
}
</code></pre>

<p>Here we've created classes for caching to Redis and MongoDB. They both implement the <code>Cache</code> interface and the required methods. I've put them in a single example, but really, they'd be in different files and potentially different namespaces. You can <a href="https://daylerees.com/php-namespaces-explained/">read more about namespaces in another article on my blog</a>.</p>

<p>Now that we have our two cache implementations, it's time to use our imagination a bit. Let's imagine that we have a config loader that reads configuration values from a PHP array. This will let users re-configure our application. Here's an example.</p>

<pre><code>&lt;?php

return [  
    'cache' =&gt; RedisCache::class
];
</code></pre>

<p>We've set the <code>cache</code> configuration option to the class name of our Redis cache. Let's further use our imagine and understand that there's a <code>config($key)</code> helper function that reads entries from the configuration. There are loads of different libraries that do configuration in many ways, or you could even use an environmental variable, but we'll use our imaginary loader for now.</p>

<p>Let's write some code that will use the <code>Articles</code> class we wrote earlier to fetch a list of articles. Here we go:</p>

<pre><code>&lt;?php

// Create our cache driver.
$cache = new config('cache');

// Inject it into a new Articles instance.
$articles = new Articles($cache);

// Load our article list.
$articlesList = $articles-&gt;fetch();
</code></pre>

<p>The first line creates a new cache instance using the class that we set in our configuration under the 'cache' key. Because we set it to <code>RedisCache::class</code> it will set <code>$cache</code> to a new instance of that class.</p>

<p>In the second line, we instantiate a new <code>Articles</code> class, injecting our cache instance into it.</p>

<p>Finally, on the third line, we use the <code>fetch()</code> method to populate an article list. Internally, our <code>Articles</code> instance has used our <code>RedisCache</code> to pull this information from Redis. (We'll assume the articles have already been written to the cache!)</p>

<p>Now here's the magic. We can change this code to use MongoDB instead of Redis to store our cache data simply by changing a single line! Here's an example:</p>

<pre><code>&lt;?php

return [  
    'cache' =&gt; MongoCache::class
];
</code></pre>

<p>By changing our cache configuration option to reference our <code>MongoCache</code> we'll receive an instance of that cache injected into the <code>Articles</code> class, and it will pull data from MongoDB. That's super handy! If we wanted to add a new cache type in advance, we'd just make another class that implements the <code>Cache</code> interface, and swap to it in the configuration.</p>

<p>Since we've used an interface for the cache, it won't work if you change the 'cache' configuration option to something that doesn't implement the <code>Cache</code> interface. It means that those read and write methods definitely exist, and we've protected any code that's using them from trying to call an instance that doesn't have them.</p>

<p>Hopefully, you now have an understanding of how you can use interfaces to make your code more robust, to enforce the 'shape' (signature) of class instances, and to make your applications more flexible. Now go out there and show the world how to use interfaces for good!</p>

<h2 id="extrainformation">Extra Information</h2>

<p>Oh, you're still here? Fine, here's some interesting topics that relate to interfaces.</p>

<h3 id="laraveldependencyinjection">Laravel Dependency Injection</h3>

<p>If you use the Laravel framework, you'll find that you can inject services into various classes, by type-hinting a 'contract' in the constructor. Interestingly, what's happening here is incredibly similar to the cache driver example above.</p>

<p>Instead of instantiating the injected instance based on configuration, Laravel checks its IoC container to find a class instance bound to that interface and then injects it directly into the class for you. That's cool, right?</p>

<p>Furthermore, Laravel uses cache adapter pattern above for its own services. You can swap out caches, databases, and more in Laravel's configuration just by changing a few options. The only difference is that Laravel hides the class names behind some friendly strings.</p>

<h3 id="youvelearnedmorethanyouthink">You've learned more than you think!</h3>

<p>By reading this article, you've actually learned more than you think.</p>

<p>Being able to inject an instance that can change type into a function is called 'Polymorphism'. I know, it's a big nasty word, but it's super useful. Essentially, if a class "looks right" and implements the required methods, then it can be passed into the function, no matter which class it is.</p>

<p>You've also learned a design pattern! Go you! You've learned about the 'adapter pattern'. That's exactly what we've created in the last example. Our classes that implement the <code>Cache</code> interface are our adapters, and they are interchangeable. Sometimes this pattern is also called the Gateway pattern when it's used to create interchangeable providers that talk to external services.</p>

<h3 id="maybeyouwantanabstractclass">Maybe you want an abstract class?</h3>

<p>If you want some method signatures with bodies and some without. For example, you want some methods to be overridden, and others must be implemented, then you probably want to use an abstract class instead.</p>

<p>Abstract classes can be used like interfaces to enforce the shape of an implementation, but you can also add fully-functional methods to them. So why not use abstract classes all the time, you ask? Well for one, they aren't meant to replace interfaces, and it's much more simple to implement multiple interfaces within a class than to create a long awkward inheritance chain.</p>

<p>For example:</p>

<pre><code>class Something implements Danceable, Jumpable, Singable  
{

}
</code></pre>

<p>Here we've got a class that implements multiple interfaces. Unfortunately, PHP can only extend a single class at a time, so imagine what it would look like trying to do the above with abstract classes. Yeah, pretty messy.</p>

<p>It's worth noting that <code>instanceof</code> works just fine on abstract classes too.</p>

<h3 id="aconstantsourceofinspiration">A constant source of inspiration.</h3>

<p>Fun fact! Interfaces can contain constants.</p>

<p>For example:</p>

<pre><code>&lt;?php

interface Cat  
{
    const FUR = 'super furry';

    const SOUND = 'meow!';
}

echo Cat::SOUND; // meow!  
</code></pre>

<p>So if you need to store some constants somewhere, it's pointless to add them to a class that can be instantiated. Just put them on an interface instead!</p>

<p>That's all there is to it!</p>

<hr>

<p>Well, that's all there is to this article. You're now a master of PHP interfaces. Are they your favourite feature now too?</p>

<p>If you found this article useful, then please leave some feedback. Also, I'm currently working really hard on a side project, it's called <a href="https://rainglow.io">Rainglow</a> and it's a collection of hundreds of syntax themes for loads of software! If you can spare a moment, please share it with your friends! That would be awesome. :)</p>

<p>If you'd like to learn more about PHP or Laravel, then there are a <a href="https://daylerees.com/books/">bunch of books that I've written on those topics</a>.</p>

<p>Thanks for reading!</p>]]></content:encoded></item><item><title><![CDATA[Favourite Color Themes]]></title><description><![CDATA[<p>I am often asked which theme is my favourite. I definitely have a bias towards dark themes for my day to day use. Truthfully, I find myself using 'Gloom Contrast' the most. It's a slightly 'greenie' version of 'Peacock Contrast' and it's been in the collection for a long time</p>]]></description><link>https://daylerees.com/favourite-color-themes/</link><guid isPermaLink="false">c3a8dd49-c971-4eca-b9aa-2adfd0425b76</guid><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Sat, 23 Dec 2017 15:51:12 GMT</pubDate><content:encoded><![CDATA[<p>I am often asked which theme is my favourite. I definitely have a bias towards dark themes for my day to day use. Truthfully, I find myself using 'Gloom Contrast' the most. It's a slightly 'greenie' version of 'Peacock Contrast' and it's been in the collection for a long time now!</p>

<p>Still, that doesn't make an interesting blog post, does it? Fine! Here are my top ten personal favourite light and dark themes.</p>

<p>What better way to share the list than to link to the <a href="https://rainglow.io">shiny new website</a> with direct links to theme previews.</p>

<h2 id="darkthemes">Dark Themes</h2>

<ol>
<li><a href="https://rainglow.io/#gloom-contrast">Gloom Contrast</a>  </li>
<li><a href="https://rainglow.io/#newton">Newton</a>  </li>
<li><a href="https://rainglow.io/#glance-contrast">Glance Contrast</a>  </li>
<li><a href="https://rainglow.io/#kiwi">Kiwi</a>  </li>
<li><a href="https://rainglow.io/#bold">Bold</a>  </li>
<li><a href="https://rainglow.io/#lichen-contrast">Lichen Contrast</a>  </li>
<li><a href="https://rainglow.io/#rainbow">Rainbow</a>  </li>
<li><a href="https://rainglow.io/#warlock-contrast">Warlock Contrast</a>  </li>
<li><a href="https://rainglow.io/#zacks-contrast">Zacks Contrast</a>  </li>
<li><a href="https://rainglow.io/#horizon-contrast">Horizon Contrast</a></li>
</ol>

<h2 id="lightthemes">Light Themes</h2>

<ol>
<li><a href="https://rainglow.io/#glance-light">Glance Light</a>  </li>
<li><a href="https://rainglow.io/#hive-light">Hive Light</a>  </li>
<li><a href="https://rainglow.io/#lavender-light">Lavender Light</a>  </li>
<li><a href="https://rainglow.io/#mellow-light">Mellow Light</a>  </li>
<li><a href="https://rainglow.io/#newton-light">Newton Light</a>  </li>
<li><a href="https://rainglow.io/#peacock-light">Peacock Light</a>  </li>
<li><a href="https://rainglow.io/#peel-light">Peel Light</a>  </li>
<li><a href="https://rainglow.io/#rainbow-light">Rainbow Light</a>  </li>
<li><a href="https://rainglow.io/#tickle-light">Tickle Light</a>  </li>
<li><a href="https://rainglow.io/#warlock-light">Warlock Light</a></li>
</ol>]]></content:encoded></item><item><title><![CDATA[New Year's Resolutions]]></title><description><![CDATA[<p>I have begun the process of revamping my side projects. You might have seen the release of my <a href="https://github.com/rainglow/vscode">VS Code color themes package</a> 'rainglow'.</p>

<p>So why has it taken so long to get back to these side projects? Well, you see, for me, the environment is everything. For the last</p>]]></description><link>https://daylerees.com/new-years-resolutions-2018/</link><guid isPermaLink="false">96489b97-219e-478b-9ab5-dba43af22c30</guid><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Wed, 13 Dec 2017 23:59:59 GMT</pubDate><content:encoded><![CDATA[<p>I have begun the process of revamping my side projects. You might have seen the release of my <a href="https://github.com/rainglow/vscode">VS Code color themes package</a> 'rainglow'.</p>

<p>So why has it taken so long to get back to these side projects? Well, you see, for me, the environment is everything. For the last few years, I've been living in houses and flats where I've had to work in the living room.</p>

<p>I'll come home from work tired, sit on the sofa, and if I try to pick up my laptop for some side projects work I'll become distracted by the TV, or my SO playing games, or any of the distractions that are common in a room that's primary function is for relaxing and entertainment.</p>

<p>When I first wrote all the books, colour schemes, libraries etc. I had my own study. I was much more productive there, and that's where I'm hoping to get back to.</p>

<p>What's different? I moved house about a month ago to a place with an extra bedroom. I've been decorating this room as my own home office. A place where I can focus on the projects that I love. I know that it sounds like such a simple thing, but already I've spent some glorious time in this room focused on writing code and content that I love to hack on.</p>

<p>Having a space devoted to work at home is wonderful, and after using the room for only a week, I'm feeling super motivated to pick up and revitalise some of my older projects.</p>

<p>So what's that going to look like? Well first let's take a look at the plan for the colour schemes project.</p>

<h2 id="rainglow">Rainglow</h2>

<p>The color schemes project has had a bit of a rebrand. I've renamed it to 'rainglow', designed a temp logo, rewritten the generation code from scratch and already released the first new theme package. For now, I'll be focusing on the really popular editors.</p>

<h3 id="1vscode">1. VS Code</h3>

<p>Code is great! I've been using it to write Javascript and devops stuff for a while now, and have found it to be a really useful editor. It's also really great to theme for. So that's what I've been focussed on. The themes for this editor <a href="https://github.com/rainglow/vscode">have already been released</a> and now it's just a matter of maintaining (and marketing) them.</p>

<h3 id="2sublimeatom">2. Sublime / Atom</h3>

<p>Sublime and atom are still great editors, so I'll be bringing support back to these platforms under the rainglow brand. They are actually really similar to theme, so that won't be a huge challenge. I'm going to try and package them up so that you can install them via package managers this time around. For now, I'll focus on syntax themes, and we might come back to the UI themes later.</p>

<h3 id="3jetbrains">3. JetBrains</h3>

<p>The JetBrains editors are heavy, but incredibly powerful. I use PHPStorm primarily in work. They are also an absolute nightmare to theme. Last time around I attempted it, but compatibility was poor. This time, I'm going to invest some time into rewriting these themes from scratch. It's going to be tough, but I hope that we'll get a better experience with rainglow for JetBrains.</p>

<h3 id="4more">4. More!</h3>

<p>I'll be looking at adding new editors, and most of all, new color combinations to all the editors! I haven't created a new color scheme for a while, so I'm looking forward to this!</p>

<h2 id="books">Books</h2>

<p>I never stopped enjoying the act of writing, but it has been another casualty of losing a study room. These projects are not forgotten, and are high on the priority list.</p>

<h3 id="1codesmart">1. Code Smart</h3>

<p>Code Smart is overdue for an update. It's still pretty effective in bringing Laravel to the masses, but is missing a few chapters that I'd like to add, and requires some updates for the newer versions of the framework. This is work that is in progress, and I'm hoping to start shipping some of this new content soon. Naturally, these will be free updates, so if you already own the book, you'll see them arrive in your copy!</p>

<p>For all those who own the book, and have been patiently waiting for an update. Thank you so much! You're the reason that I do this. I'm truly grateful for all the support.</p>

<h3 id="2morewriting">2. More Writing</h3>

<p>I've got an urge to write something new. I'm currently exploring a few different options, varying from more advanced PHP titles, to beginner titles for Javascript and React. I could also experiment with some devops titles. When it comes to writing, I have more ideas than I have the days to work on. So hopefully I can narrow it down to the book that will have the most value to the masses, and get working on it. Watch this space!</p>

<h2 id="otherstuff">Other Stuff!</h2>

<p>Just a bunch of other stuff! Once the two priorities above are out of the way. I'm hoping to revamp some of my older projects, tackle some new ideas, build some new and interesting learning resources. Just a bunch of 'stuff'.</p>

<p>The TL;DR of this article is: I have some space to think, and now I'm back to building, writing, and fiddling with cool technology. Watch this space!</p>]]></content:encoded></item><item><title><![CDATA[The Artist and the Engineer]]></title><description><![CDATA[<p>I have my own personal under-bed monster, and it's in the form of another breed of developer.</p>

<p>In truth, this article is less about that which torments me and more about two different types of developer that I've identified. I like to call these two types of developers the 'artist'</p>]]></description><link>https://daylerees.com/the-artist-and-the-engineer/</link><guid isPermaLink="false">ac59e190-6018-4df2-a82c-02d1eedc6129</guid><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Wed, 22 Jun 2016 20:33:56 GMT</pubDate><content:encoded><![CDATA[<p>I have my own personal under-bed monster, and it's in the form of another breed of developer.</p>

<p>In truth, this article is less about that which torments me and more about two different types of developer that I've identified. I like to call these two types of developers the 'artist' and the 'engineer.' Both are skilled developers, but let's take a look at where they differ.</p>

<p>The artist seeks beauty in all things. They choose a wallpaper instead of using the stock one. They apply different colour schemes to their editor. They care when an image on a website has one extra pixel of padding to the right when compared to the left.</p>

<p>These types of developers enjoy patterns (visual ones) and consistency. They like it when things are aligned. They want their bookshelf to be ordered by the colour of the cover, or alphabetically, or any evident pattern. For definite, will they be labeled as 'that OCD person'?</p>

<p>I am one of these people. I am the artist. I'm fine with it. Our nature rarely raises anger from the 'engineer'. We'll keep things pretty, and they will still be functional.</p>

<p>Unfortunately, this peace does not work from both directions. Let's take a look at the 'engineer'.</p>

<p>The engineer does not give a flying pig about your consistency, or your patterns. They are a skilled developer, but they care more about the functionality of their code than its general appearance.</p>

<p>You think they have time to ensure their comment format is consistent across the project? Oh hell no. They don't have time to waste on that. If you encourage them to do so, they will resent you.</p>

<p>My monster isn't under the bed at all, is it? It's the 'engineer' sitting over there who doesn't understand my desire for visual consistency.</p>

<p>Consider the following snippets of PHP code. Don't worry; this isn't a highly technical article. We won't get complicated.</p>

<pre><code>&lt;?php

namespace Laravel\Application;

use Illuminate\Support\Str;  
use Illuminate\Http\Request;  
use Illuminate\Http\Response;  
use Illuminate\Support\Collection;  
use Illuminate\Container\Container;  
use Illuminate\Database\Eloquent\Model;  
</code></pre>

<p>This is the work of an 'artist'. They like the way that the namespaces slope. If they add a new import, they'll likely take the time to ensure that the slope still obeys the rules. It's visually pleasing, and it allows them to enjoy their class. Their code isn't just instructions; it's artwork.</p>

<p>In contrast, here's what the 'engineer' has done.</p>

<pre><code>&lt;?php

namespace Laravel\Application;

use Illuminate\Container\Container;  
use Illuminate\Database\Eloquent\Model;  
use Illuminate\Http\Response;  
use Illuminate\Http\Request;  
use Illuminate\Support\Collection;  
use Illuminate\Support\Str;  
</code></pre>

<p>This solution is perfectly fine. The code still executes as before, but the 'engineer' has instead decided to order his imports alphabetically (or in most circumstances, not order them at all.)</p>

<p>Let's take a look at some more work from the artist.</p>

<pre><code>/**
 * The event dispatcher instance.
 *
 * @var \Illuminate\Contracts\Events\Dispatcher
 */
protected $events;

/**
 * The IoC container instance.
 *
 * @var \Illuminate\Container\Container
 */
protected $container;

/**
 * The route collection instance.
 *
 * @var \Illuminate\Routing\RouteCollection
 */
protected $routes;

/**
 * The currently dispatched route instance.
 *
 * @var \Illuminate\Routing\Route
 */
protected $current;  
</code></pre>

<p>The artist has provided consistent comments for all of their class properties. Having this consistency makes their class more 'balanced', more visually pleasing, and more artful.</p>

<p>In contrast, let's look at what the monst.. 'engineer' has done.</p>

<pre><code>/**
 * The event dispatcher instance.
 *
 * @var \Illuminate\Contracts\Events\Dispatcher
 */
protected $events;

/**
 * @var \Illuminate\Container\Container
 */
protected $container;

/**
 * The route collection instance.
 */
protected $routes;

/**
 * The currently dispatched route instance.
 *
 * @var Route
 */
protected $current;  
</code></pre>

<p>The engineer provides descriptions only when they think that they are necessary. To add a description to every property for the sake of consistency would be a waste of their time.</p>

<p>Fully qualified namespaces, or relative ones? Surely it doesn't matter. PHPDoc will parse them just the same.</p>

<p>Note that all of the examples are perfectly legal with respect to the 'PSR-2' PHP coding standard, but instead the difference focus on layout, style, and consistency.</p>

<p>Which of the two developers is correct? As much as it pains me, I think that neither of them is wrong.</p>

<p>Both are skilled developers, and both write code that is fully functional and delivers the solutions they seek. It's unfortunate that the engineer is most likely to make the artist feel uncomfortable.</p>

<p>Speaking as an 'artist' (at least in the context of this article), when I write code that is inconsistent, I instantly lose an appreciation for that code. It's tainted, it's messy, and I don't love it anymore.</p>

<p>I'd never consider punishing an engineer for their way of coding; it simply wouldn't be fair. However, I do believe that consistency can have its advantage when working in a team.</p>

<p>When in a team, imposing rules that extend further than a standard code-style guide will result in code that will appear it has been written by a single individual. This makes it much easier to "scan" and to understand (at least, over time). Training the engineers to follow this practice is a difficult task. Habits form over time, and can become difficult to retrain. Especially when they do not "feel" anything for the consistent visual appearance of code.</p>

<p>If you'd like to observe the artist and the engineer in a non-professional environment, then consider the world of open source.</p>

<p>Observe the likes of Taylor Otwell (Laravel) and Fabien Potencier (Symfony). Both incredibly gifted developers, and creators of the most popular PHP frameworks on the 'market'.</p>

<p>Examining both frameworks, and the code they have contributed (or maintained/reviewed) I'd suggest that Taylor is the 'artist' and that Fabien is 'the engineer.'</p>

<p>In fact, I'd also be as bold as to suggest that artist types are more attracted to the Laravel framework and that engineers are more attracted to Symfony. Of course, this suggestion is based purely on personal observations.</p>

<p>The programming world is a diverse mix of personalities, and I'm incredibly grateful for this. Whether you are an artist, an engineer, or something entirely different. Please continue to write fantastic code.</p>

<p>Do you think that you identify as an artist or an engineer? Why not leave a comment to let me know!</p>

<p>Thanks for reading!</p>]]></content:encoded></item><item><title><![CDATA[I'm Dayle - AMA]]></title><description><![CDATA[<p>I thought it might be fun to keep an AMA (Ask Me Anything) style blog post on my site. Feel free to ask your questions in the comments, or to <a href="https://twitter.com/daylerees">tweet them at @daylerees</a>. If I receive questions, I'll update this post.</p>

<p>I'm Dayle Rees. Self-published author, one of the</p>]]></description><link>https://daylerees.com/im-dayle-ama/</link><guid isPermaLink="false">bfffe786-74db-4435-98d2-b17e63760127</guid><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Tue, 24 May 2016 20:55:21 GMT</pubDate><content:encoded><![CDATA[<p>I thought it might be fun to keep an AMA (Ask Me Anything) style blog post on my site. Feel free to ask your questions in the comments, or to <a href="https://twitter.com/daylerees">tweet them at @daylerees</a>. If I receive questions, I'll update this post.</p>

<p>I'm Dayle Rees. Self-published author, one of the first Laravel users, conference speaker, development educator, lover of pandas, colour scheme engineer and  developer at <a href="https://www.crowdcube.com/">Crowdcube.com</a>. Ask me anything!</p>

<hr>

<h3 id="whatisyourfavouritecoloursianzhttpstwittercomsianz">What is your favourite colour? - <a href="https://twitter.com/Sianz">Sianz</a></h3>

<p>This had to come up didn't it! I'm quite a boring guy actually. My favourite colour is Black. It goes with anything. I'm never going back!</p>

<h3 id="asidefromlaravelwhatisyourfavouritephpframeworkthemattbrunthttpstwittercomthemattbruntstatus735213736336711680">Aside from Laravel, what is your favourite PHP Framework - <a href="https://twitter.com/TheMattBrunt/status/735213736336711680">TheMattBrunt</a></h3>

<p>Honestly, I like all of the frameworks. They all serve a purpose, and are tools for creating things. You've asked me to pick a favourite, though. I'd have to say Symfony. There are some components to the framework that haven't just enhanced the framework, but have changed the PHP world entirely. Thanks for the HTTP Foundation Fabpot!</p>

<h3 id="whatarethemostimportantthingsyouvelearntwhenwritingpublishingyourbookssteviephilhttpstwittercomsteviephil">What are the most important things you’ve learnt when writing &amp; publishing your books? - <a href="https://twitter.com/steviephil">Steviephil</a></h3>

<p>Great question Steve. I've learned a lot from the experience, but I'll keep the answer to two major points. First of all, I've gained confidence as a developer, but learned that I absolutely suck at grammar. My spelling is okay, but I absolutely abuse the comma. I'm probably doing it right now. I'm learning to be better at it, and I'm really hoping it's starting to show in my newer books. Secondly, I've learned that everyone has something to share and teach others. I wasn't very confident when I started writing, and I wasn't sure that I had anything to offer other developers. Now I'm teaching thousands of developers to code. There's always someone with less experience than yourself, and it's your duty to share your knowledge. I also learned that writing is bloody hard work! Thanks for the question!</p>

<h3 id="whyphpvsrubynightshade003httpstwittercomnightshade003">Why PHP vs. Ruby? <a href="https://twitter.com/NightShade003">NightShade003</a></h3>

<p>Because it's better. But seriously, if I hadn't come across Laravel when I did, I might have been a Ruby developer. I know Ruby, and I've built some stuff with Rails and Sinatra in the past. Both are fantastic frameworks. I'm a fan of design, minimalism and simplicity. The nature of the ruby language makes it the obvious choice, but Laravel was even more appealing. I think these days Laravel, mostly due to it growing as a framework, isn't as plain and simple as it was. That's ok, though; I've grown too.</p>

<h3 id="okjamescjohnshttpstwittercomjamescjohnsh00zf1shhttpstwittercomh00zf1shgavd_ukhttpstwittercomgavd_uksnogmarryoravoidcraigcodesmarvellyhttpstwittercomcraigmarvelley">OK - <a href="https://twitter.com/jamescjohns">@jamescjohns</a>, <a href="https://twitter.com/h00zf1sh">@h00zf1sh</a>, <a href="https://twitter.com/gavD_UK">@gavD_UK</a>. Snog, marry or avoid? - <a href="https://twitter.com/craigmarvelley">Craig 'Codes' Marvelly</a></h3>

<p>Essential question Craig. I think I'd have to snog Jon Morgan because he's irresistable. I'd probably marry James Johns because I spend most of my time with him anyway. That leaves Gavin Davies. I'm gonna have to avoid him, because I'm worried that clever sausage might show me up when it comes to dev skills. What would you choose?</p>

<h3 id="whoisthemosthandsomeanddevilishlycharismaticdesigneryouknowkyeehttpstwittercomkyee">Who is the most handsome and devilishly charismatic designer you know? - <a href="https://twitter.com/kyee">Kyee</a></h3>

<p>Honestly, I've never seen one. Every time I try to lay eyes on them I'm blinding by a flash of ego.</p>

<h3 id="whatwouldyouliketodoifyouwerentadeveloperareyouthinkingaboutdoingsomethingelseantoineaugustihttpstwittercomantoineaugusti">What would you like to do if you weren't a developer? Are you thinking about doing something else? <a href="https://twitter.com/AntoineAugusti">Antoine Augusti</a></h3>

<p>If I wasn't a developer, I'd still have to do something creative. I think I'd be an artist or a designer. Maybe a musician? Of course, this is a dream world because I'm terrible at drawing and you never want to hear me play the guitar.</p>

<p>Am I thinking about doing anything else? Interesting question. I do sometimes think about it. Over the past few years I've been exposed to the PHP community, there are some parts of it that I love, and there are some other parts of it that make me want to flip my table and become a potato farmer. I'm not sure if development is good for you in the long run, not when you're not all that sane in the first place. My father is a builder, and is very proud of this work. He's been doing it for longer than I've been alive, and to this day he puts pride into everything he does. He strives for perfection, not to impress his peers, but for fulfilment. While I'd love to be this way, in twenty years time I don't think I'll feel that way about the code that I write.</p>

<p>I've dabbled a bit with management, and found it surprisingly rewarding. I like helping people to make the most out of themselves, and management is a great outlet for that. Maybe in a few years I'll try my hands a CTO-style role again. We'll see. Since I've stolen your identity Antoine, maybe I should be an international man of mystery?</p>

<h3 id="whatisyourfavouritejavascriptframework">What is your favourite Javascript framework? - عاطف بن علي</h3>

<p>Honestly, I hate Javascript. For the longest time PHP got some schtick for being a simple language, and having been messy, but have you seen the Javascript ecosystem lately? Every time I come back to it the whole toolchain has shifted.</p>

<p>I suppose if I have to chose one, then for server side I chose Express. It's the closest to Rails/Laravel. Client side, I'd have to choose React lately. Although, I had a lot of love for Backbone. In a world where every JS framework was trying to do everything for you, Backbone had the balls to say "do it your way".</p>

<h3 id="whatsthebestlaravelbooktobuynewtoitandwannalearnideallyfrompapernotascreeneighty9httpstwittercomiice89">Whats the Best laravel book to buy? New to it and wanna learn ideally from paper not a screen. - <a href="https://twitter.com/iiCe89">Eighty9</a></h3>

<p>There are a bunch of great Laravel authors, but I'm honestly not sure which of them have physical books. I'd say keep away from anything by Packt. I'm sure their authors are great, but I think they are a terrible company, and I'd rather not support their efforts. I am planning to release print copies of Code Smart and PHP Pandas, but I'm not sure on an exact date.</p>

<h3 id="shouldpeoplebotherwithformaleducationordiverightintodevelopmenttogetwheretheywanttobealexgarretthttpstwittercomalexjgarrett">Should people bother with formal education or dive right into development to get where they want to be? - <a href="https://twitter.com/alexjgarrett">Alex Garrett</a></h3>

<p>Great question Alex. I think that, as with most things, it depends on your sithation. If you're in a quiet place, and aren't very good at selling yourself, then you might need a degree on your CV to get that first job. Personally, although I went to Uni, and hold a degree, I didn't really enjoy it. I think that development is a skill that is driven by the love of creating things, and the curiosity of learning to make those things more efficient. If you're good at what you do, you learn fast, you've got a modern company in mind, and you're great at selling yourself, then by all means, skip that degree and start building things. If you choose to bypass formal education, why not learn through <a href="https://www.codecourse.com/">Codecourse</a>? :)</p>]]></content:encoded></item><item><title><![CDATA[Marketing is harder than writing]]></title><description><![CDATA[<p>Soon, my <a href="https://leanpub.com/composer-php">latest book on Composer</a> will be available for free. I thought I'd write an article to explain the reasoning behind this move.</p>

<h2 id="whyisitfree">Why is it free?</h2>

<p>Originally, I had planned for my latest book to be a premium one, with a low cost due to its size. Post-release</p>]]></description><link>https://daylerees.com/marketing-is-harder-than-writing/</link><guid isPermaLink="false">1394aad8-67d3-4e7a-86f8-478476e017f2</guid><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Tue, 17 May 2016 18:24:10 GMT</pubDate><content:encoded><![CDATA[<p>Soon, my <a href="https://leanpub.com/composer-php">latest book on Composer</a> will be available for free. I thought I'd write an article to explain the reasoning behind this move.</p>

<h2 id="whyisitfree">Why is it free?</h2>

<p>Originally, I had planned for my latest book to be a premium one, with a low cost due to its size. Post-release it was clear that I had completely underestimated the market. I'm always hearing from people who use Composer, but don't truly understand it, or where it fits into their workflow. They simply operate on snippets provided from their framework, or indeed, Google. It seems that I was wrong. Within the first two days of the book being available (the first day always has the most sales) Composer had sold ten copies.</p>

<p>It's clear that I should have done my research on this one. Perhaps I should treat my books a little more like the products that I work on.</p>

<p>While I do enjoy writing and do enjoy helping others to learn new skills, I'm forced to treat my writing like a business. I work a full-time job and am writing my books in any free time that I get. I'm not a rich guy; I'm still saving up for my first mortgage. Instead of using that time for rest, video games or spending time with the family, you'll find me writing. To make that justifiable to the people around me, I need to turn a profit.</p>

<p>Here's the truth about how profit works at Leanpub.</p>

<p>First, you need to price your book. You must take into consideration that a 20% sales tax will be applied on top and that Leanpub will take 10% of royalties. Now tax.. well that's never going to change, and Leanpub's royalties are more generous than most.</p>

<p>Let's say that we price the book at $20. It will be $24 on the site. When the book goes live, and a purchase is made, we first need to subtract Leanpub's cut. So the user pays $24, the taxman gets $4; Leanpub gets $2, and you get $18.</p>

<p>Only, when you're me, you don't get $18. This is because I live in the UK. First, you need to convert the currency, which doesn't always work in your favor. Let's convert into my native currency, Great British Pounds.</p>

<pre><code>$18.00 = £12.45
</code></pre>

<p>Unfortunately, the deductions don't stop there. If you work full time (like I do), then you'll need to declare this extra income to the taxman. I do self-assessment tax, which is inclusive of my general income. Now I'm hardly Jay-Z, but I am an experienced developer, so I make a comfortable salary. </p>

<p>This means that I have no tax-relief on the amount from the books, and have to pay tax at a rate of 40%. That's almost half of the profit. Suddenly, the profit from each sale becomes £7.47.</p>

<p>Now let's apply the same process to Composer, which was priced at $14, and after all deductions, this comes in at £5.59.</p>

<p>Overall sales over the first couple of days would amount to £55.98, which is about as much as a PS4 game in the UK.</p>

<p>Now I'm more than grateful to my readers who have purchased a copy, and trust me when I say that your support is deeply appreciated, but as a business that doesn't make sense.</p>

<p>I could likely make more than £50 from an hour of consulting. Instead, I spent countless hours writing, reviewing, formating and preparing to release Composer.</p>

<p>If I were to leave Composer with its ten sales, then the work wouldn't be over. I'd have to support that title regarding fixes and future chapters over countless months.</p>

<p>By making Composer free (and refunding the existing sales) I'm able to provide the Composer title "as is" and focus on more important things.</p>

<p>I'd much rather turn zero profit, and have people actually read what I've written.</p>

<p>This is why Composer is now free. If you'd like a copy, <a href="https://leanpub.com/composer-php">you'll find it here</a>.</p>

<h2 id="howdoesthiseffectotherbooks">How does this effect other books?</h2>

<p>Code Smart has a higher premium and has sold more copies than Composer. It has sold nowhere-near the amount of copies that Code Happy and Code Bright sold, but they were during what I considered "prime time" for learning Laravel. This was to be expected.</p>

<p>In terms of time spent, and profit made vs. potential for contracting/freelancing/consulting, then Code Smart is still not a wise business move. It demands more time than any other title, and I won't be done adding chapters anytime soon.</p>

<p>Code Smart is the exception to my "treat it like it's business" rule. The readers are the same who helped me get started with my writing career. I feel connected to them, and want to help them learn more. I'll continue releasing content for Code Smart until I feel that it's done, even if the profits wane.</p>

<h2 id="whyarentyourich">Why aren't you rich?</h2>

<p>Oh man, I wish! I'd have my own red panda if that were true. I never really intended for my "writing" to become "a thing." It was just a gamble. So I suppose the question to ask is, why aren't my books selling very well?</p>

<p>I'd chalk that up to a few things. I think it's mostly about marketing. I have zero clue how to market. The only persons within "my business" so to speak, are myself and the translators. I do all the covers, prepping, reviewing, etc, etc. I do the marketing. I do it badly.</p>

<p>Right now, I rely on the fact that I have a fairly large Twitter following. Just over 10k or so people, who are primarily developers. It's my biggest reach. If you try to promote anywhere else, especially in public forums, then you tend to get attacked for self-promotion. So I don't do that.</p>

<p>Most of my followers are Laravel developers, so it stands to reason that they will be more likely to buy a Laravel book than any other topic. The problem is that I don't want to be writing about Laravel forever. This is the third time I've written a Laravel book, and while I still think the framework is great, and I'm happy to be providing knowledge to my readers, the writing just isn't exciting any more. I'd prefer some new challenges, and to approach some different topics.</p>

<p>So to turn this into a profitable business, I'd have a few options I suppose. Feel free to hit me up if you have other ideas!</p>

<ol>
<li>Use a bunch of marketing services, and hope that the profit outweighs their fees. This would be difficult because I don't know where to start looking.  </li>
<li>Hire a marketing guy, turning the venture into a small business. No guarantee that this will work either, and certainly a bunch more paperwork involved.  </li>
<li>Kickstarter (I don't have the funds to bootstrap effectively) a new publishing company. Write some awesome books that everyone can understand. Get more authors, turn profit, tour the world, buy a Red Panda.  </li>
<li>Give up and just write for fun, but less frequently.  </li>
<li>Write for a publisher, lose all creative control, have dull books, and be a sad, sad emo.</li>
</ol>

<p>Well, the third one is an exciting option, and holy-moly would I love to give it a go. I think it's a bit of a pipe dream, though. There's no way I could compete with Manning or O'Reily, and it's clear that I don't know the first thing about running a business.</p>

<p>Right now I'm learning towards four. Which is fairly saddening, but is the only way I'm going to keep any standard of living. Probably do some contracting on the side, and maybe re-approach writing once I've made my mortgage deposit.</p>

<h2 id="whatsnext">What's next?</h2>

<p>Great question! I had grand plans to release a broad series of books for beginners, but I worry that I'll spend years of my life doing that, and likely go broke in the process.</p>

<p>Instead, I'll put my work cap on and try to drive my decisions by the numbers. Do a little research to find out what people are interested in, and hopefully, it won't be another Laravel book.</p>

<p>I think I'm going to ditch the other planned titles, and see how you guys feel about another title I have in mind. For a long time now I've wanted to write a patterns book for PHP.</p>

<p>It would be design patterns using examples and language that can be understood by anyone. I find that the other material out there is either written for another language (and not all patterns make sense for PHP) or are way too complicated for those getting started.</p>

<p>They don't need to be. Patterns aren't all that complicated. You're probably using some already without knowing that they have names.</p>

<p>I'd love to throw a bunch of hints and tips in this book on how to make your code more extensible. How to write code and toolage for your fellow developers to work with. This is where I thrive in my day-to-day work. You'll find me writing tools and processes to simplify work for my colleagues. I love it.</p>

<p>I don't really care if it doesn't sell, it's just something that I've wanted to do for a long time. I genuinely believe that it will help people, as long as I can bring it to their attention.</p>

<p>I'm going to continue to work on Code Smart, and to do a little research on the patterns book at the same time. I'm hoping the idea is intriguing, but I need to confirm that before I write another Composer.</p>

<h2 id="wasitworthit">Was it worth it?</h2>

<p>Oh hell yeah. It may not be the most profitable use of my time, but some money is always useful, and money isn't even the biggest part of it.</p>

<p>Through my writing, I've got to meet and enjoy the company of so many wonderful people. I've taught people skills that have got them better jobs and thus live a better quality of life. I've received feedback from people who don't understand English so well but find my books easy to read. I'm really glad that these people have a way to learn.</p>

<p>I love my readers, and I'm forever grateful that they've been part of my career as an author. To the 10 or so folks that bought Composer, thank you! I hope you find what you were looking for from the book, and that it proves useful to you. Don't worry; I'll find a way to refund your purchase so you'll get the book for free too!</p>

<p>Once I work out what's next, I'll be sure to let you know. If you've got some ideas on how I can market, or where I should take my talents, then please do get in touch. I'd love to hear it.</p>

<p>Until then, enjoy the updates to Code Smart. Enjoy your free copy of Composer, and enjoy learning!</p>]]></content:encoded></item><item><title><![CDATA[Code Smart will arrive this month]]></title><description><![CDATA[<p>Hey there code wranglers! I think it's about time I gave you fine folk another update on how Code Smart is coming along.</p>

<p>I've been working hard over the last months to get Code Smart in a shape that's fit for release. My previous titles have released in simple form,</p>]]></description><link>https://daylerees.com/code-smart-arrives-this-month/</link><guid isPermaLink="false">28e63746-b0fe-45e1-84f8-38424f892bde</guid><category><![CDATA[Books]]></category><category><![CDATA[News]]></category><category><![CDATA[CodeSmart]]></category><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Tue, 12 Apr 2016 18:44:03 GMT</pubDate><content:encoded><![CDATA[<p>Hey there code wranglers! I think it's about time I gave you fine folk another update on how Code Smart is coming along.</p>

<p>I've been working hard over the last months to get Code Smart in a shape that's fit for release. My previous titles have released in simple form, and have built into grand epics over time. However, Code Smart will start with all of the Code Bright content updated for the latest version of Laravel.</p>

<p>This means that on launch, Code Smart will have around 400 pages, and that will only be the beginning. From there we'll continue to explore additional features, and techniques for the framework. I'm committed to delivering <em>at least</em> one additional chapter per week.</p>

<h2 id="previouscontent">Previous Content</h2>

<p>As I've mentioned in previous updates. I'll be reusing the content of Code Bright as a base for Code Smart. This doesn't mean that the content will be copied and pasted. Sure, the same chapters on basic components that you know and love will be there, but this time they've had a few upgrades. Let's take a look at what has changed.</p>

<p><strong>Laravel 5.</strong></p>

<p>All of the content has been updated for the latest version of Laravel. Extra functionality has been added, deprecated functionality has been removed. File paths and locations have been updated to match the new application layout. You'll be a cutting edge Laravel pro in no time at all!</p>

<p><strong>Improved Examples</strong></p>

<p>The examples in Code Bright were a little messy. Every example in Code Smart has been updated in terms of formatting and content. Every example segment will feature full syntax highlighting, a title, and an example number (to easily make notes or  report errata).</p>

<p><strong>Code Standards</strong></p>

<p>All code examples have been upgraded to be compatible with the PSR-2 PHP code standard. We're also using new features that have been added to PHP since Code Bright. Goodbye legacy array syntax!</p>

<p><strong>Testing</strong></p>

<p>All code examples within the book have an associated unit test. This means that if the version of Laravel updates, and something isn't valid any more, then I'll know right away. I'll update the book as soon as possible.</p>

<p><strong>Stories</strong></p>

<p>The stories have been removed. Given feedback, I've decided that removing the stories will allow you to quickly get to the content that you need. Don't worry, terrible cheesy humour has not been removed.</p>

<p><strong>Polish</strong></p>

<p>All content has had a bit of a refresh, and should be of higher quality. It will still be familiar, but should read better than it previously did.</p>

<h2 id="gettingstarted">Getting Started</h2>

<p>The whole introductory chapters of the title have been replaced. This means that I've now simplified the process of getting started with Laravel.</p>

<p>For example, we'll learn how to get started with homestead, which means that you can be up and running with the framework in a few minutes, and you won't need any system administration knowledge at all.</p>

<p>I've also added some new chapters on basic framework concepts, request lifecycle, and general hints and tips on application design.</p>

<h2 id="writingforyou">Writing for you!</h2>

<p>As you know, my titles don't have a set completion. I'm constantly adding new content to them. This time around, you'll be driving that content.</p>

<p>I'll be announcing votes (likely on twitter) for which new piece of content should be written next, and reacting to the features and services of Laravel that you want to learn about.</p>

<p>We won't stop until this is a Laravel masterpiece that is worthy of the 'Code' line of succession.</p>

<h2 id="sowhenthefudgecanigetit">So when the fudge can I get it?</h2>

<p>Well, it's clear that there has been a bunch of demand for the title, and I'm truly flattered and grateful for all your interest in the book. As you know, I just won't release something to meet a deadline. I'll release a book when I feel that it's ready.</p>

<p>The good news is that Code Smart is almost ready. I'm adding the finishing touches for a first release, and I'm happy to announce that <strong>it will be available later this month</strong>.</p>

<p>While I've not set an exact price yet. I'm also pleased to announce that the new title will be cheaper to purchase than Code Bright was.</p>

<p>This is my way of thanking you all for supporting my self-published works over the years. Without your support, and your investment in Code Happy, Code Bright and PHP Pandas, I simply wouldn't have been able to release another book. The evolution from hacker to self-published author has been one hell of an adventure, and I'm excited to see what comes next.</p>

<p>It's time that I get back to working on the book so we can get it in your hands sooner. Please be sure to <a href="https://twitter.com/daylerees">follow me on twitter</a> as I do most of my announcements there, and you'll be the first to hear when the book is available for purchase.</p>

<p>Thanks for your support and patience!</p>

<p>Dayle.</p>

<p>xx</p>]]></content:encoded></item><item><title><![CDATA[Code Smart Questions Answered]]></title><description><![CDATA[I'm here today to bring you some good news. An update on 'Code Smart'!]]></description><link>https://daylerees.com/code-smart-questions-answered/</link><guid isPermaLink="false">171252fc-938a-4e5a-bf90-28f842026738</guid><category><![CDATA[Books]]></category><category><![CDATA[Laravel]]></category><category><![CDATA[CodeSmart]]></category><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Sun, 17 Jan 2016 16:06:03 GMT</pubDate><content:encoded><![CDATA[<p>Howdy readers!</p>

<p>I'm here today to bring you some good news. An update on 'Code Smart'! I announced Code Smart a while ago, and many of you lovely folks have been asking how it's been progressing. Let's answer all those questions in a single blog post, shall we?</p>

<h2 id="whyisittakingsolong">Why is it taking so long?</h2>

<p>Great question! First, let me start by explaining that my writing career is definitely a side project. You see, unlike subscription based learning mechanisms, books have a "spike" of income, and then they slowly trickle away. Given that I choose to self-publish, the income from the books will sadly never replace my yearly salary as a developer.</p>

<p>For this reason, I'll never be able to "live" off the books, and they will remain a project that I work on in my spare time.</p>

<p>For the last couple of years, I've been working for an exciting startup in the parking industry. Having made my mark on the company, I've now moved on to a new startup.</p>

<p>In my previous startup, I was Head of Engineering, a role that meant working long hours to build the future of the company. It left little free time to work on my writing, and for this I must apologize.</p>

<p>I'm currently working as a Lead Software Engineer over at <a href="https://www.crowdcube.com/">Crowdcube</a>. They are much better with their working hours, and the work is much less stressful for me.</p>

<p>For this reason, I've been granted additional time to work on the books, and it's brought Code Smart back into my focus.</p>

<h2 id="whynotupdatecodebright">Why not update Code Bright?</h2>

<p>Code Bright was designed for Laravel 4. Granted, much of the content is similar, but things like locations of files are different, and some deprecated content is present.</p>

<p>I'd still like to keep Code Bright a valid resource for Laravel 4, since I know of a good many people who are still tied to that version. With every major release of the framework, I like to take an opportunity to start fresh and try some new learning methods.</p>

<p>Having said this, I'm a developer. I don't like to repeat myself. There are a great number of chapters from Code Bright that are <strong><em>almost</em></strong> correct for Laravel 5. Writing the same content again would drive me crazy, and if you've read my books before, then you know that I'm crazy enough already!</p>

<p>For this reason, I've decide to reuse those chapters. However, they aren't going to remain identical. For each chapter that I'll be borrowing from Code Bright, I'll be doing the following.</p>

<ul>
<li>Updating the content to represent Laravel 5.</li>
<li>Improving wording, grammar and spelling.</li>
<li>Improved formatting to bring the content up to speed with my modern books.</li>
</ul>

<p>Once again, these chapters will remain as great tutorials, and even greater reference material. I've taken a look at the content that can be kept relevant for Laravel 5, and have found ~300 pages.</p>

<p>This means that <strong>the book will start with 360 pages</strong> of learning content for the new framework iteration. From here, I'll be introducing new chapters at regular intervals to cover a wealth of new and exciting features that have been introduced into the framework in recent years.</p>

<p>I'm also approaching the intro chapters of the book from a new angle, to ease the learning process. There's a few new chapters at the start that are going to help strengthen your framework knowledge. The installation chapter has been completely re-written to work with per-project instances of Homestead, which is going to be a wonderful way for newcomers to start learning.</p>

<p>When this title is complete, it's going to be a mahooosive whopping bookshelf-breaker of a Laravel bible. Trust me. You're going to love it!</p>

<h2 id="whataboutthestories">What about the stories?</h2>

<p>Haha! The stories were like Marmite. Some people love them, some people... not so much!</p>

<p>For this reason, I'm going to leave the stories in the book (and write some new ones!), but label them as a first 'sub-chapter' called Storytime. This way, you can easily skip past this content if you want to.</p>

<p>In honesty, I think the stories are part of the learning experience. Normally, the story will be a direct reference to the component described in the chapter. It creates a memory-mechanism for learning. It's hard for a Code Bright ready to think about the routing methods without also thinking about Browsy McRequest!</p>

<h2 id="sowhencanwehaveit">So when can we have it?</h2>

<p>I've almost completed the "refreshing" of the Code Bright chapters, and have written a whole new beginning to the book. So the first iteration of Code Smart will likely be released within a month or two.</p>

<p>From here, I'll lay out a schedule for regular updates to the title, for everyone to enjoy the new and wonderful features included with Laravel.</p>

<p>I'm sorry it's taken so long to get here guys, but I'm incredibly greatful for your continued interest in the series.</p>

<p>I promise that Code Smart is going to be a book worth waiting for.</p>

<p>Take it easy!</p>

<p>Dayle.</p>

<p>xx</p>]]></content:encoded></item><item><title><![CDATA[PHP: The Composer Lock File]]></title><description><![CDATA[Learn about the PHP Composer lock file, including how and when to use it. Solve the greatest mystery in the world.]]></description><link>https://daylerees.com/the-composer-lock-file/</link><guid isPermaLink="false">b308be4d-86b3-4e2b-9e06-1b3453164547</guid><category><![CDATA[Development]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Composer]]></category><dc:creator><![CDATA[Dayle Rees]]></dc:creator><pubDate>Sun, 23 Aug 2015 22:46:44 GMT</pubDate><content:encoded><![CDATA[<p>Everywhere that I go, conference, the supermarket, the dentist, building sites, people always ask me about the <a href="https://getcomposer.org/">Composer</a> lock file. It's a mystery that seems to cause confusion all across the globe. Well, boys and girls, I'm here today to de-mystify the lock file once and for all.</p>

<p>Composer is a PHP application that manages the versions of the PHP libraries, tools and frameworks that we use in our application. For the purpose of this article, I'm going to assume that you've at least build a composer-powered application previously.</p>

<p>Let's begin with a new project and very much imaginary project. It begins with a <code>composer.json</code> file. This file is used to list the versions of our PHP dependencies that we wish to install. Our <code>composer.json</code> file contains three packages.</p>

<pre><code>{
    "require": {
        "assassins/ezio":   "1.1.0",
        "assassins/edward": "1.1.2",
        "templars/shay":    "1.1.*",
    }
}
</code></pre>

<p>We've clearly defined the version of two of our packages, but with our third <code>templates/shay</code> is a little more flexible, and we don't care about the patch version parameter. Anything beginning with <code>1.1</code> will do just fine.</p>

<p>Now it's worth noting that these are fake packages. Don't go and try to install them. I promise you, they won't work. I've just been playing way too much Assassin's Creed lately.</p>

<p>You could say that the <code>composer.json</code> is a very 'rough' guide to the versions that should be installed. It's not precise, because we have these wildcard versions available to us. It's a ballpark blueprint for our application dependency hierarchy.</p>

<p>We don't have a <code>composer.lock</code> file at the moment, but the second that we run the <code>composer install</code> command.</p>

<p>Behold, we've executed <code>composer install</code> and the mysterious <code>composer.lock</code> file has appeared. If you take a look inside, you'll notice that it's pretty big!</p>

<p>Now it's time for the big reveal. You see, while your <code>composer.json</code> file is a rough guide to the dependency versions that Composer should install, the <code>composer.lock</code> file is an <strong><em>exact</em></strong> record of the dependency versions that have been installed.</p>

<p>That's right, it's recording what Composer has installed for you, right down to the commit hash. Here's a little example:</p>

<pre><code>"source": {
    "type": "git",
    "url": "https://github.com/templars/shay.git",
    "reference": "98c313c831e5d99bb393ba1844df91bab2bb5b8b"
},
</code></pre>

<p>You see that big long string? That's the exact commit version that was installed when Composer followed the directions in your <code>composer.json</code> file. It also keeps track of all the versions of your dependencies' dependencies. Even your dependencies' dependencies' dependencies. Even... Well, you get the idea. Your entire application dependency hierarchy will have their versions 'locked' in your <code>composer.lock</code> file.</p>

<p>Why is this useful? Well it's simple. Go ahead and delete your <code>vendor</code> directory. That will remove all of the installed Composer packages that are your applications dependencies.</p>

<p>It's time to run <code>composer install</code> again. This time, Composer will see that you have a <code>composer.lock</code> file in the directory. Instead of finding compatible versions of your dependencies to fulfil the <code>composer.json</code> file, it will install the <strong><em>exact</em></strong> version of your dependencies as defined in your <code>composer.lock</code> file.</p>

<p>This means that we've got the <strong><em>exact</em></strong> version of our dependencies that we had installed before we deleted the vendor directory. That's pretty nifty, right?</p>

<p>Time and time again I hear the question...</p>

<blockquote>
  <p>Should I version my <code>composer.lock</code> file?</p>
</blockquote>

<p>The answer to that question should now be apparent. If you want to record the <em>exact</em> versions of your dependencies that have been used for your application, then <strong>yes</strong> you should version your lock file. In most sithations, this will be true.</p>

<p>If you're working with a team, versioning the lock file will ensure that you're all working using the exact same versions of your dependency packages. This can be really useful when debugging errors that happen for only one developer.</p>

<p>If you're deploying your application using git, and you version your lock file, you can be sure that the <em>exact</em> version of your dependencies that you tested locally with, will be used in production.</p>

<p>Why is it so important to be using the <em>exact</em> versions of your dependencies?</p>

<p>Let's consider that you don't version your lock file. You <code>composer install</code> and because of the <code>1.1.*</code> version of the <code>templars/shay</code> package, Composer installs version <code>1.1.4</code>.</p>

<p>Between this install, and the time that you deploy to your production environment, the <code>templars/shay</code> team have released version <code>1.1.5</code>. Ouch! Unfortunately, the <code>1.1.5</code> version of the package has a serious bug in it.</p>

<p>When you deploy your application to production,  Composer installs <code>1.1.5</code> of the package, and your application explodes, destroying the whole universe, as per Abstergo's master plans.</p>

<p>You see, if you'd have versioned your lock file, the <code>composer install</code> on production would have respected the lock file, and used version <code>1.1.4</code> of <code>templars/shay</code> that you had tested in production. The world would be safe for the time being.</p>

<p>In a sentence...</p>

<blockquote>
  <p>The Composer lock file is a guarantee of the dependency versions that will be installed, right down to an individual commit level.</p>
</blockquote>

<p>Finally, what would cause the <code>composer.lock</code> file to change? All the time, I see people using <code>composer update</code> whenever they update their <code>composer.json</code> file to get the new packages. This is a bad move! You should be using <code>composer install</code> , because it will install your new package without updating the versions of your other packages. This would be much safer.</p>

<p>Here's a list of some actions that will update your <code>composer.lock</code> file.</p>

<ul>
<li>You run <code>composer install</code> for the first time, and the <code>composer.lock</code> file is updated to the installed versions of the dependencies.</li>
<li>You run <code>composer install</code> after adding a new package, and the exact version of the new package is added to the <code>composer.lock</code> file.</li>
<li>You run <code>composer update</code>, and all of your packages are updated to their latest versions according to the <code>composer.json</code>. This will update the exact version records in the <code>composer.lock</code> file.</li>
<li>You run <code>composer update package/name</code> and the version of the specified package is updated to it's latest version observing the package version hint in <code>composer.json.</code> The exact version in the <code>composer.lock</code> file is updated to respect this.</li>
</ul>

<p>This means that <code>composer install</code> is a "safe" command, and will only add packages to your <code>composer.lock</code> file.</p>

<p>The command <code>composer update</code> is a "risky" command, because it will directly manipulate the version numbers held within your <code>composer.lock</code> file.</p>

<p>Hopefully, you've now deciphered the mystery of the <code>composer.lock</code> file, and also have a craving to play the Assassin's Creed games. (You should. They are fantastic!)</p>

<p>If this guide has helped you learn a thing or two about the Composer lock file, then please consider sharing this article with your friends, so that they too, will learn the secret behind mankind's greatest mystery since "Why is Kevin Bacon an absolute &amp;%£$£?".</p>

<p>Thanks for reading!</p>]]></content:encoded></item></channel></rss>