<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abed Halawi on Medium]]></title>
        <description><![CDATA[Stories by Abed Halawi on Medium]]></description>
        <link>https://medium.com/@mulkave?source=rss-1ea6c1a3d2fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MwByuYosPq9EAqFz_AlZ5w.jpeg</url>
            <title>Stories by Abed Halawi on Medium</title>
            <link>https://medium.com/@mulkave?source=rss-1ea6c1a3d2fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 04:58:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mulkave/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Becoming One — Lucid 1.0 & The Road Ahead]]></title>
            <link>https://medium.com/vinelab-tech/becoming-one-lucid-1-0-the-road-ahead-6c31b06916f1?source=rss-1ea6c1a3d2fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c31b06916f1</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[lucidarch]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Abed Halawi]]></dc:creator>
            <pubDate>Thu, 03 Dec 2020 21:43:32 GMT</pubDate>
            <atom:updated>2020-12-04T00:22:24.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cdhuybMQ6KXY6KcEy-A1Q.jpeg" /></figure><h3>Becoming One — Lucid 1.0 &amp; The Road Ahead</h3><p>I cannot believe that it’s been 4 years since the inception of Lucid into open source, it feels like yesterday. Throughout this term we’ve been launching Lucid * Laravel applications and the more we use it, the more we know its worth, especially after a long time passes and we revisit old code only to say “wow, how would we have navigated this project if it weren’t for this architecture?”, and we said that countless times.</p><p>It is true that Lucid has been in “unstable” mode (version &lt; 1), only because we subconsciously knew that something somewhere needed to change, we just didn’t know what it is until a few months back when we started re-evaluating some decisions and identified enhancements that can uplift our codebases. Nevertheless, we’ve been in production with Lucid since 2015 and it’s always been a great success! However, adding features, upgrading Laravel projects and versions has always been a hassle due to the fragmentation of sources:</p><ul><li>foundation-laravel and console-laravel are the packages required to get Lucid</li><li>The only way to begin with a Lucid project is to clone a boilerplate from lucid-architecture/laravel or lucid-architecture/laravel-microservice, which isn&#39;t the best approach compared to requiring a composer package that fits better in the PHP ecosystem for what Lucid is offering</li></ul><p>For the TL;DR version head over to the <a href="https://github.com/lucidarch/lucid/releases/tag/v1.0.0">release Changelog</a>, or continue reading to know the story.</p><h3>Consolidation</h3><p>The first step to solve this is to consolidate Lucid’s core into a single installable package, now available at <a href="https://github.com/lucidarch/lucid">https://github.com/lucidarch/lucid</a>.</p><p>There are several advantages to a single repository:</p><ul><li>Issue tracking: One repository to report issues, ask questions and provide feedback</li><li>Support: as soon as <a href="https://github.blog/2020-05-06-new-from-satellite-2020-github-codespaces-github-discussions-securing-code-in-private-repositories-and-more/#discussions">GitHub discussions</a> are publicly available it will also be the official forum besides StackOverflow</li><li>Contribution: there will be one repo to star, watch for updates and contribute to, instead of four</li><li>Roadmap: will be also visible in a single place once published</li></ul><h3>Package vs. Boilerplate</h3><p>As expressed previously it is favourable in the PHP ecosystem to provide such offering as a package that you can install rather than a boilerplate, for the obvious reason that it becomes cumbersome to maintain, not to mention that it’s extremely difficult to include in an existing project without having to plan a codebase migration which causes a halt in the progress that no business is willing to suffer.</p><p>On the contrary, adding a package to an existing project and gradually moving pieces is a much smoother experience, and actually a realistic one.</p><p>With the new package lucidarch/lucid a simple composer require lucidarch/lucid would suffice, be it new or existing, and with the new commands to initialize a variant init:micro and init:monolith it will be all that&#39;s required to scaffold the initial structure.</p><h3>Supported Versions</h3><p>As for supporting several versions, with a package this becomes a breeze, as of the time of this writing it is supporting the most recent versions are supported as per the matrix below. See <a href="https://docs.lucidarch.dev/installation/#versions--compatibility">the docs</a> for the latest compatible versions:</p><ul><li>Laravel: 8, 7, 6, 5.5 (LTS)</li><li>PHP: 8.0, 7.4, 7.3, 7.2 , 7.1</li></ul><h3>Knowledge Base</h3><p><strong>Documentation</strong> is the number one proponent for a successful open source project. Up until this point, the only content has been the readme files of the corresponding repositories, which covers briefly what Lucid is about and how to use it, but certainly is nowhere near adequate for wide adoption. The folks who’ve done it on their own (around 300 that i know of), I consider them heroes who were able to pick up the concept with very little information and take it from there on their own. And as far as I’ve learned from their feedback, they’ve astonishingly succeeded! If you’re one, I salute you!</p><p>The problem is that with little information on how to go about the different cases you may encounter, we left too much space for imagination in order to understand the intended message. Therefore, the new thorough documentation is finally in place at: <a href="https://lucidarch.dev/">https://lucidarch.dev</a> and it is just the initial version. I’ll be constantly adding to it the more updates and feedback come in.</p><p><a href="https://dev.to/lucidarch"><strong>dev.to blog</strong></a> is also a place to share content about our experience with Lucid so far and as we go, as well as update announcements and anything that may come in the future.</p><p><em>P.S. Stay tuned for the upgrade guide! Currently being finalised to make it a smooth transition of your applications to Lucid 1.0.</em></p><h3>Modularity</h3><p>Not everyone wants the same thing, there is no one-size fits all solution to our applications, and not everyone wants it all every time for every case. So it’s been decomposed to become modular and flexible. Choose whichever pieces of the puzzle that fit you best, and use them. You want Feature and Job only? no services? You got it, just go head and use the CLI to generate whichever unit from the stack and use it. Familiarity would still be there since it’s the same units that we’re used to, only that they might either exist as they should, or not exist at all. Consistency is key, and with this model it is secured as such.</p><p>This approach allows Lucid to be used in an even wider variety of applications that wouldn’t have been possible with the boilerplates, because cloning them meant a commitment to the entire stack and structure, while our applications require more malleability since we start small and grow gradually, and now the architecture will be there for you at every step in the way.</p><h3>Cohesion</h3><h3>With Laravel</h3><p>At the time of inception, Laravel was at v4, and since then many improvements have been made and were adopted by Lucid (silently), and the plan is to keep it coherent with Laravel’s offering, carefully choosing features to avoid redundancy and confusion, concentrating on complementing it in any future decision.</p><h3>Within</h3><p>Up until v1 there’s been a significant gap between both variants — Micro and Monolith — specifically that Monolith files have been placed in /src as root and the /app directory has been slightly neglected. As for Micro, it is more in accord with Laravel&#39;s initial structure at the/app directory, as well as generating Lucid units that&#39;s been placed in different locations:</p><p><strong>Previously</strong></p><ul><li>Data: Micro app/Data , Monolith src/Data</li><li>Services: Micro N/A, Monolith src/Services</li><li>Domains: Micro app/Domains , Monolith src/Domains</li><li>Domain Tests: Micro tests/Domains/&lt;domain&gt;, Monolith src/Domains/&lt;domain&gt;/Tests</li></ul><p>This is no longer the case. The gap between variants have been closed in favour of increased conformity and familiarity with Laravel, and will be the case moving forward.</p><p><strong>Now</strong></p><p>It will be the same for both variants:</p><ul><li>Data: app/Data</li><li>Domains: app/Domains</li><li>Services: app/Services</li><li>Domain Tests: app/Domains/&lt;domain&gt;/Tests</li></ul><p>This increases the degree of familiarity when working on any of the variants and switching between them, and most importantly moving an application from one to the other barely requires any cognitive effort.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7lr897rZ7ok8qO6d.png" /></figure><h3>About Previous Contributions</h3><p>Open issues from all repositories will be transferred to the new lucidarch/lucid repo.</p><p>Credit goes to everyone below for contributing; waiting for you in the fresh repo!</p><h3>Maintainers</h3><ul><li><a href="https://github.com/KinaneD">Kinane Domloje</a></li><li><a href="https://github.com/harris21">Harris Raftopoulos</a></li></ul><h3>Contributors</h3><p>A note on contribution, it is not only done through code, but also in sharing knowledge through blog posts, questions and feedback; keep them coming!</p><ul><li><a href="https://github.com/websmurf">Adam van Dongen</a></li><li><a href="https://github.com/adibhanna">Adib Hanna</a></li><li><a href="https://github.com/alexgiuvara">Alex</a></li><li><a href="https://github.com/adiachenko">Alexander Diachenko</a></li><li><a href="https://github.com/imrealashu">Ashish Singh</a></li><li><a href="https://github.com/bjdelange">Bert-Jan de Lange</a></li><li><a href="https://github.com/lezhnev74">Dmitry Lezhnev</a></li><li><a href="https://github.com/kohlerdominik">Dominik Kohler</a></li><li><a href="https://github.com/haralddoderer">Harald Doderer</a></li><li><a href="https://github.com/jbaron-mx">Jesus Baron</a></li><li><a href="https://github.com/jonasemde">Jonas Emde</a></li><li><a href="https://github.com/zeraist">Jose Marques</a></li><li><a href="https://github.com/Lazir">Lazir</a></li><li><a href="https://github.com/glorand">Lorand Gombos</a></li><li><a href="https://github.com/speccode">Maciej Czerpiński</a></li><li><a href="https://github.com/pietdevries94">Piet de Vries</a></li><li><a href="https://github.com/bart">Rene Bartkowiak</a></li><li><a href="https://github.com/rzougabenoma">rzougabenoma</a></li><li><a href="https://github.com/sharik709">Sharik Shaikh</a></li><li><a href="https://github.com/vitoo">Victorien Plancke</a></li></ul><p>I promise you that it hasn’t been any easier to work with Lucid and add to or modify it. Local setup is extremely simple and there’s a CI setup to ensure backward compatibility according to the supported version matrix. In addition to the fact that there will be no confusing branching model in several repositories to deal with, just a single repository with its release versions. How relieving!</p><h3>Identity &amp; Branding</h3><p>Notice the change in the org username on GitHub, renamed lucid-architecture to lucidarch. This change is an identity change to the alias of Lucid Architecture - lucidarch - where moving forward Lucid&#39;s online presence will be (where available) as such &quot;{platform}/lucidarch&quot; (except for Twitter because it&#39;s already taken so there&#39;s lucid_arch now).</p><p>The choice for the alias was straight forward — Lucid Arch — short for architecture, also resembles arches which in architecture are used to <strong>span an opening and to support loads from above.</strong> Call it a great coincidence, but it also aligns with Lucid’s objective.</p><h3>The Road Ahead</h3><ul><li>Frequent updates: With a single repository it is easier to contribute and thus easier to adopt and provide new releases</li><li>New Laravel features that make sense to have their Lucid counterpart will do so almost instantly, as well as Laravel updates and upgrades will be available upon release since there will be no boilerplate to prepare</li><li>Enriching the knowledge base will be the utmost priority to try and spread the word about our experience</li><li>Stay tuned for the upgrade guide so that you can transition your existing applications and leverage upcoming updates</li></ul><h3>Communication Channels To Tune In To</h3><ul><li><a href="https://github.com/lucidarch/lucid/releases">Releases on GitHub</a></li><li><a href="https://twitter.com/lucid_arch">Lucid on Twitter</a> &amp; my personal account <a href="https://twitter.com/mulkave">mulkave</a> for announcements</li><li><a href="https://reddit.com/r/lucidarch">Reddit</a> announcements in addition to cross posts of interesting content from similar communities</li><li><a href="https://dev.to/lucidarch">dev.to/lucidarch</a> for knowledge sharing</li><li><a href="https://lucid-slack.herokuapp.com/">Slack</a> to gather around the campfire</li></ul><h3>Vision</h3><p>Finally, I would like to close by laying out the vision for Lucid’s future.</p><p>Fundamentally, Lucid is a mirror of our values; it is to express our fascination by the world of programming and our intention to contribute parts that can be assembled to create a living structure. Like seeds turning into a plant, expands from within and gradually complicates itself yet sustains an elegent shape that guides our understanding and requires the least amount of cognitive effort to comprehend.</p><p>The ability to share Lucid code in a “pluggable” way is also in the horizon, because there is so much of what we do that’s already been done and we’re also working on similar things at the same time, being able to grab a functionality that you’re familiar with its structure and API effortlessly would make it even easier and faster to assemble.</p><p>Most importantly, remember to enjoy the journey!</p><p><em>Originally published at </em><a href="https://lucidarch.dev/blog/announcements/becoming-one-and-the-road-ahead/"><em>https://lucidarch.dev</em></a><em> on December 3, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c31b06916f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vinelab-tech/becoming-one-lucid-1-0-the-road-ahead-6c31b06916f1">Becoming One — Lucid 1.0 &amp; The Road Ahead</a> was originally published in <a href="https://medium.com/vinelab-tech">Vinelab · Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Operations — The Lucid Architecture]]></title>
            <link>https://medium.com/vinelab-tech/introducing-operations-the-lucid-architecture-bad45f259a1d?source=rss-1ea6c1a3d2fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/bad45f259a1d</guid>
            <category><![CDATA[lucid-architecture]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Abed Halawi]]></dc:creator>
            <pubDate>Wed, 25 Jan 2017 08:11:55 GMT</pubDate>
            <atom:updated>2020-12-15T19:10:40.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*pC3VDcLjL-MEAfYGrOJniA.jpeg" /></figure><p>Since its inception, the core concept has been solid and is being proven by the day. One major aspect of Lucid is that it fits the wide variety of use-cases without neither amending nor working around the architecture.</p><p><strong>Update 15–05–2020:</strong> After 5 years passing since the announcement of Lucid, and due to the demand and adoption of this architecture, it has become essential to have a standalone place for proper documentation and resources. And it’s finally <a href="https://docs.lucidarch.dev/">here</a>! Check it out for the up-to-date information and join the community.</p><p>The good news is that we’ve been using it ever since, and it has proven to be reliable and saved us a huge amount of tech dept. I hope it does the same to you too.</p><p>Nevertheless, the below is the inception of operations and they’re covered more <a href="https://docs.lucidarch.dev/operations">in-depth in the docs</a>. Enjoy reading!</p><h4>The Battle Field</h4><p>At Vinelab, we have recently launched 14 services based on the <a href="https://github.com/lucid-architecture/laravel-microservice">Laravel-Microservice</a> project, some of them have multiple instances running, amounting a total of 34 instances of these services in a microservice architecture setup based on AWS EC2 Container Service. Although it is not the biggest number you’ve heard of when it comes to services, but this is only the beginning with much more to come.</p><p>These services vary in their nature and the responsibilities they hold, from scheduled tasks that fetch and update data from 3rd-party services, services that deal with data storage using messaging queue, and services to crunch and analyse the collected data from a variety of data stores, such as Neo4j, MongoDB and Redis. Which grants us the opportunity to battle-test the Lucid Architecture even further, and we couldn’t be happier about it.</p><p>As the use-cases became more complex in logic, Features and Jobs alone did not suffice, a hidden gem in the depth of the architecture that always shines when needed, but never spoken about. <strong>Operation</strong>.</p><h4>Definition</h4><p>By definition it is “an organised activity involving a number of people” and in Lucid terms it is: <strong>An organised activity involving a number of Jobs</strong>.</p><h4><strong>Purpose</strong></h4><p>Lucid’s primary objectives was to <strong>cure the Redundancy Syndrome — </strong>those few lines of code that keep repeating here and there. It has done a good job organising them in re-usable components called Jobs, yet we still find Jobs in different Features being repeated in the same sequence, which is a remaining symptom of redundancy in a minor form.</p><blockquote>One main reason why we group Jobs in an Operation is to avoid a Job calling other Job(s), which is an anti-pattern that breaks the code’s behavioural expectation. We wouldn’t be able to assume that a Job is calling another Job internally, we can only observe the steps at the Feature level.</blockquote><h4>Example</h4><p>Suppose we have two Features for creating and updating an article, CreateArticleFeature and UpdateArticleFeature respectively. The following steps (in short) are to be performed in both Features:</p><ol><li>Validate article metadata (title, body, tags)</li><li><strong>Process the article’s cover photo</strong> (which consists of the following steps)</li></ol><ul><li>Validate dimensions to make sure the minimum requirements are met</li><li>Generate multiple variations of the photo based on cropping</li><li>Upload generated variations to a CDN</li><li>Save the photo with its variations using the retrieved CDN URLs</li></ul><p>3. Save the article with the cover photo (including variations)</p><p>4. Return the saved article</p><p>Here’s a sample of what these Features would look like:</p><h4>CreateArticleFeature</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f35dd4f455ba65728f48b162ed1c4291/href">https://medium.com/media/f35dd4f455ba65728f48b162ed1c4291/href</a></iframe><h4>UpdateArticleFeature</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2811654609dc1b627a6ade74ff17d94/href">https://medium.com/media/e2811654609dc1b627a6ade74ff17d94/href</a></iframe><blockquote>These Features are incomplete, just for demo purposes missing use statements.</blockquote><p>We will not dive too deep into what the Jobs do since their names are quite self-explanatory but as you can see the // process cover photo part is the same, creating redundancy, while the rest of the jobs differ.</p><p>To eliminate that, <strong>Operation</strong> was introduced before <a href="https://www.youtube.com/watch?v=wSnM4JkyxPw">Lucid was announced to the public at LaraconEU in August 2016</a>, but never spoken about. And here’s how it works:</p><p>An Operation groups a set of Jobs that are often used together in a specific sequence to achieve a functionality. it lives at the same level of the Feature (in an Operations directory similar to Features), so when it’s a Lucid Monolith this directory is at the Service level (i.e. src/Services/Api/Operations/SomeOperation.php) as for a Lucid Microservice it is at app/Operations/SomeOperation.php.</p><p>A generator has been implemented by <a href="https://medium.com/u/7dc9458fc8f9">Ali Issa</a> which we will use to generate an operation and group these jobs together. Using the lucid <a href="https://github.com/lucid-architecture/console-laravel">CLI</a> run the following:</p><p>In a monolith, say with an Api service:</p><pre>lucid make:operation ProcessArticleCover api</pre><p>For a microservice you eliminate the api for there isn’t a service to consider.</p><p>Moving the jobs into the operation, we end up with this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e3d795189ee73edd7bb949f3bb13beb/href">https://medium.com/media/9e3d795189ee73edd7bb949f3bb13beb/href</a></iframe><p>Now we update <strong>CreateArticleFeature</strong> from earlier and we get:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/453ad7797ed34aa35780861663fe80dc/href">https://medium.com/media/453ad7797ed34aa35780861663fe80dc/href</a></iframe><p>And the same goes for <strong>UpdateArticleFeature</strong>. As you can see it’s neat, more readable, and used similarly as a Job.</p><p>If you would like to know about the concept behind the Lucid Architecture, here’s the original post.</p><p><a href="https://blog.vinelab.net/the-lucid-architecture-concept-ad8e9ed0258f">The Lucid Architecture — Concept</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*HQ35d78x4TDYudvD_dKgHw.png" /></figure><p>If you are using the Lucid Architecture or want to give it a try, get in touch by joining the community on the Slack channel:</p><p><a href="http://lucid-slack.herokuapp.com/">Join Lucid on Slack!</a></p><p><em>Happy Coding!</em> ✌🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bad45f259a1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vinelab-tech/introducing-operations-the-lucid-architecture-bad45f259a1d">Introducing Operations — The Lucid Architecture</a> was originally published in <a href="https://medium.com/vinelab-tech">Vinelab · Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing Composer Packages for Laravel 5 — The Lazy Way]]></title>
            <link>https://medium.com/vinelab-tech/developing-composer-packages-for-laravel-5-the-lazy-way-1a99c454f842?source=rss-1ea6c1a3d2fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a99c454f842</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Abed Halawi]]></dc:creator>
            <pubDate>Fri, 14 Aug 2015 10:51:38 GMT</pubDate>
            <atom:updated>2015-08-14T10:51:38.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RQ0RxUQrESzICauSVvR81A.png" /></figure><p>If you’re like me, missing workbench since it has been cut out of Laravel starting version <strong>5</strong> the development process has been a bit frustrating and not so straight forward. In addition to the likelihood to have your packages in a separate directory yet linked locally to a project or more, for development purposes only.</p><p>These are the current approaches that I’m aware of (if you know more please mention them in a response):</p><ul><li>Push an initial VSC-driven version of the package to <a href="http://packagist.org/">packagist</a> and require it in Composer then implement it in the <em>vendor</em> folder, and if you mistakenly or intentionally run a <em>composer update</em>, Oops! You lost all your changes. (There could be ways to avoid this but they’re just “dirty workarounds”).</li><li>Using a local absolute path to your package in the <a href="https://getcomposer.org/doc/05-repositories.md#repositories"><em>Repositories</em></a> section of your <em>composer.json</em> file, but also requires you to keep your VCS up-to-date and commit every change you would like to test.</li></ul><p>Both of these solutions didn’t cut it for my preferred workflow.</p><h4>The Solution</h4><p>Inspired by @joeholdcroft’s <a href="https://github.com/composer/composer/issues/1299#issuecomment-48536596">issue comment</a> it is rather simple to tell composer to load your local library, all you have to know is the Namespace of the package you are developing.</p><p>In your Laravel 5 project:</p><ul><li>Open <em>bootstrap/autoload.php</em></li></ul><blockquote>In case you’re wondering what this file is, it is the first file ever run in the Request/Response lifecycle, you can see that in your <em>index.php.</em></blockquote><ul><li>Find this line</li></ul><pre>require __DIR__.’/../vendor/autoload.php’;</pre><blockquote>At the time of this writing it can be found at line 17</blockquote><ul><li>Given that the namespace of my package is <em>Mulkave/DaPackage</em> living in <em>/Users/mulkave/Developer/php/packages/DaPackage </em>and follows <a href="http://www.php-fig.org/psr/psr-4/"><em>PSR-4</em></a> autoloading with its “root” folder being <em>src</em>, and the project where I would like to test it is in <em>/Users/mulkave/Developer/sandbox/DaProject</em></li><li>Change that line to be something like this:</li></ul><pre>$autoloader = require __DIR__.’/../vendor/autoload.php’;<br>$autoloader-&gt;setPsr4(‘Mulkave\\DaPackage\\’, ‘/Users/mulkave/Developer/php/packages/DaPackage/src’);</pre><ul><li>In the Laravel project run:</li></ul><pre>composer dump-autoload</pre><p>Now composer knows about it, you can add your Service Provider to your app config and have it recognised and registered.</p><p>Note that the dependencies of the package have to also be either <em>autoloaded</em> the same way (from the vendor folder <em>i.e. /Users/mulkave/Developer/php/packages/DaPackage/vendor)</em>, or required within the project’s <em>composer.json</em> file. To me, compared to the other solutions this is tolerable since it’s not much of a frequent thing that you would be doing during development.</p><blockquote>If you’ve hacked this your way, I’d love to know about it in a response to this post.</blockquote><p>🐘 <em>Happy Packaging!</em> ✌︎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a99c454f842" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vinelab-tech/developing-composer-packages-for-laravel-5-the-lazy-way-1a99c454f842">Developing Composer Packages for Laravel 5 — The Lazy Way</a> was originally published in <a href="https://medium.com/vinelab-tech">Vinelab · Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Lucid Architecture — Implementation]]></title>
            <link>https://medium.com/vinelab-tech/the-lucid-arhitecture-implementation-be99abd108cf?source=rss-1ea6c1a3d2fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/be99abd108cf</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[ddd]]></category>
            <category><![CDATA[lucid]]></category>
            <dc:creator><![CDATA[Abed Halawi]]></dc:creator>
            <pubDate>Thu, 30 Jul 2015 20:42:33 GMT</pubDate>
            <atom:updated>2020-12-15T19:37:16.190Z</atom:updated>
            <content:encoded><![CDATA[<p>Using PHP &amp; Laravel to represent <a href="https://medium.com/vine-lab/the-lucid-architecture-concept-ad8e9ed0258f">the Lucid architecture</a> in code</p><p>Following up from our <a href="https://lucidarch.dev/concept">concept</a>, here you will find the coding representation with a simple example of building a <em>National Citizen Record Directory</em>.</p><p><strong>Update 15–05–2020:</strong> After 5 years passing since the announcement of Lucid, and due to the demand and adoption of this architecture, it has become essential to have a standalone place for proper documentation and resources. And it’s finally <a href="https://docs.lucidarch.dev/">here</a>! Check it out for the up-to-date information and <a href="http://lucid-slack.herokuapp.com/">join the community</a>. Also, <a href="https://lucidarch.dev/">the website</a> lays out the benefits of using an architecture.</p><p>The good news is that we’ve been using it ever since, and it has proven to be reliable and saved us a huge amount of tech dept. I hope it does the same to you too.</p><p>Nevertheless, the below is the first version so if you’re curious enjoy reading!</p><h3>Deprecated!</h3><p><strong><em>On 07–08–2016</em></strong></p><p>This version of the implementation is now an old one; there’s a much easier, straight-forward one that you can find in the <a href="https://docs.lucidarch.dev/getting-started">Getting Started guide</a>.</p><blockquote>If you prefer skipping the details and head to code you can find it on <a href="https://github.com/lucidarch/lucid">GitHub</a>.</blockquote><h3>Code Structure</h3><p>Starting with a fresh Laravel installation (Laravel 5.1 is the latest version at the time of this writing)</p><pre>composer create-project laravel/laravel Lucid</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*ThOKyMcHX7Ez4B1YA9jRCQ.png" /></figure><blockquote>This is what it initially looks like, and this represents our <strong>Framework</strong>.</blockquote><p>According to our architecture the <em>App</em> namespace should be replaced by <em>Framework </em>to expressively represent itself<em>:</em></p><pre>&gt; php artisan app:name Framework</pre><p>For clarity and because we can, we will be implementing this architecture in a separate folder outside of the framework, calling it <strong>src</strong> (cheesy I know but if you have a better one please suggest it in a comment 😏)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*Rbb9nu1FbGNOQpw3v93_Xg.png" /></figure><p>This is how our <strong>src</strong> folder looks like</p><p>Our example consists of two services</p><ul><li><em>Site </em>representing the part where privileged agents and agencies register people for citizenship, used on-site.</li><li><em>Office</em> used by officials in head offices — allowed to grant and revoke citizenships.</li></ul><p>But for simplicity and the sake of the example we will only be dealing with the Site here.</p><h4>Configuration</h4><p>First we need to tell composer about our namespace — called <em>Directory — </em>inside of <strong>src</strong><em>.</em></p><pre>&quot;psr-4&quot;: {</pre><pre>  &quot;Framework\\&quot;: &quot;app/&quot;,</pre><pre>  &quot;Directory\\&quot;: &quot;src/&quot;</pre><pre>}</pre><p>Run this and composer will know all about our directory.</p><pre>&gt; composer dump-autoload</pre><h4>Autoloading</h4><p>As mentioned in the <a href="http://medium.com/vine-lab/the-lucid-architecture-concept-ad8e9ed0258f">Lucid architecture concept</a> services have their own routes, controllers and declare their own dependencies. Let’s leave the dependencies part for now and focus on implementing our routes and controllers. To do that we will follow Laravel’s HTTP structure as a convention which means our routes will live in <em>src/Services/Site/Http/routes.php </em>and <em>src/Services/Office/Http/routes.php<br></em>and our controllers in<br><em>src/Services/Site/Http/Controllers/*</em> and <em>src/Services/Offices/Http/Controllers/*</em></p><p>If you’re well acquainted with Laravel you must be thinking that this takes a lot of tweaking in order to tell Laravel’s <em>RouteServiceProvider</em> that we need to load these routes within their corresponding namespaces while it loads them in the default <em>App\Http\Controllers</em> namespace. Not just that, but we’ll also need <em>Http\Middleware, Config</em>, <em>Resources (views)</em>, <em>Console, </em>and most importantly <em>ServiceProviders — </em>per service each — hence <a href="https://github.com/caffeinated/modules/wiki">caffeinated/modules</a> to the rescue! It provides exactly that, but calls them modules (our services = modules)</p><ul><li>Install the <em>Caffeinated/Modules</em> package by adding the following to your <em>composer.json</em></li></ul><pre>&quot;caffeinated/modules&quot;: &quot;~2.0&quot;</pre><blockquote>Consult the <a href="https://github.com/caffeinated/modules/wiki/Installation">official installation docs</a> for different Laravel versions, I am using Laravel 5.1.</blockquote><ul><li>Publish it’s configuration file with</li></ul><pre>&gt; php artisan vendor:publish</pre><p>By default, <em>Modules </em>will look into the <em>app/Modules</em> directory while we need it to look into our <em>src/ </em>instead, to do that open <em>config/modules.php</em> and find the line that says</p><pre>&#39;path&#39; =&gt; app_path(&#39;Modules&#39;),</pre><p>Change it into</p><pre>&#39;path&#39; =&gt; app_path(&#39;../src/Services&#39;),</pre><ul><li>Generate the Site’s boilerplate by running:</li></ul><pre>&gt; php artisan module:make Site</pre><blockquote>There must not be a directory at <em>src/Services/ </em>called<em> Site, </em>otherwise the Caffeinated/Modules package will scream with errors.</blockquote><ul><li>Update <em>src/Services/Site/module.json </em>to match your liking.</li></ul><pre>{<br>  “name”: “Site”,<br>  “slug”: “site”,<br>  “version”: “1.0”,<br>  “description”: “Site is the agent&#39;s access to the directory”,<br>  “enabled”: true<br>}</pre><blockquote>Good thing about such configuration is the trivial property “description” although it might seem silly but in a couple of months and for new devs it will help them understand the role of each of your services.</blockquote><ul><li>Go to <em>src/Services/Site/Providers/RouteServiceProvider.php<br></em>By looking at these two lines</li></ul><pre>use Illuminate\Routing\Router;<br>use Caffeinated\Modules\Providers\RouteServiceProvider as ServiceProvider;</pre><p>You can see that we’re violating the rules of transparency between the Framework and the Services and it’s the role of the Foundation to provide it so we need to create a foundational <em>RouteServiceProvider</em> that does the work for us.</p><ul><li>Copy the generated <em>RouteServiceProvider </em>into <em>src/Foundation/Providers/RouteServiceProvider.php</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c8e53c0e7531bc912439a87cc4cfc29/href">https://medium.com/media/0c8e53c0e7531bc912439a87cc4cfc29/href</a></iframe><p>Hmm… That doesn’t look quiet exactly like the one generated by <em>Caffeinated</em>/<em>Modules </em>and the reason is that I’ve added a little magic to it to minimise the inheriting class’s requirements as much as possible, which makes our Site’s <em>RouteServiceProvider </em>look like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d71c1637aa7ac5f7fe49c2991d2ac614/href">https://medium.com/media/d71c1637aa7ac5f7fe49c2991d2ac614/href</a></iframe><p>All you have to do is extend the Foundation’s <em>RouteServiceProvider</em> and declare the service name. (pretty neat huh!)</p><h4>Request Lifecycle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSxW1MZpzgrERByaZ7wT4A.jpeg" /><figcaption>Lucid Request Lifecycle</figcaption></figure><p>It is not essential that every request goes through the whole lifecycle otherwise it would be unnecessary overhead so feel free to plug a response at any stage if need be. One piece that also might be added is a <em>Service Middleware </em>that goes after the <em>Foundation Middleware</em> but it was ommited on purpose for it might make the figure a little confusing.</p><h4>Routes &amp; Controllers</h4><p>Now that we’ve setup our routes to be recognised let’s create our first Site route that accepts the agent’s input of a citizen’s data and passes them on to the corresponding controller.</p><p>In <em>src/Services/Site/Http/routes.php </em>within the existing group with the ‘site’ prefix</p><pre>Route::post(&#39;/citizens&#39;, &#39;CitizenController@register&#39;);</pre><p>Now we need to create our <em>CitizenController </em>but before we do that let’s do the usual and create our foundation controller to be extended by services’ controllers. In <em>src/Foundation/Controller.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f3360b61366cdf79be874f192b7b29b/href">https://medium.com/media/3f3360b61366cdf79be874f192b7b29b/href</a></iframe><p><em>ServesFeaturesTrait</em> is a decorator for <em>DispatchesJobs </em>with one added method <strong>serve($feature, $arguments)</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/225462bcbec5e9fc8a59a8a764048f94/href">https://medium.com/media/225462bcbec5e9fc8a59a8a764048f94/href</a></iframe><p>Now we create our feature to be served by the <em>CitizenController</em></p><ul><li>Create the feature in <em>src/Services/Site/Features/RegisterCitizenFeature.php</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b99e637905a3430b9711cc7601acf8e/href">https://medium.com/media/3b99e637905a3430b9711cc7601acf8e/href</a></iframe><ul><li><em>src/Services/Site/Http/Controllers/CitizenController.php</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c8215024eb8e4e251a8181709a3a264/href">https://medium.com/media/6c8215024eb8e4e251a8181709a3a264/href</a></iframe><h4>Features</h4><p>Our first feature will be registering a citizen inside the national directory through the Site. We will start by building an abstract feature class for all our features to extend and have the capability of dispatching jobs. The perfect place for such classes is (you guessed it) Foundation.<br>In <em>src/Foundation/Feature.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37ef2011e76382c11216daa58cead8e1/href">https://medium.com/media/37ef2011e76382c11216daa58cead8e1/href</a></iframe><blockquote>We use a fork of <a href="https://github.com/symfony/symfony-docs/blob/2.7/contributing/code/standards.rst">Symfony’s coding standard</a> which you can find <a href="https://github.com/Vinelab/php-coding-standards">on GitHub</a>.<br>It’s <a href="http://www.php-fig.org/psr/psr-2/">PSR-2</a>, hence the <strong>Abstract<em> </em></strong><em>prefix in the class name</em>.</blockquote><p>Let’s explain that feature class a bit:</p><pre>namespace Directory\Foundation;</pre><ul><li>declaring our feature’s namespace.</li></ul><pre>implements SelfHandling</pre><ul><li><em>SelfHandling</em> tells Laravel to call the <em>handle()</em> method on this class instead of looking for a separate handler class elsewhere such as <em>RegisterCitizenFeatureHandler.</em></li></ul><pre>use DispatchesJobs;</pre><ul><li><em>DispatchesJobs</em> provides the capability of marshalling and dispatching jobs with their required dependency injections etc.</li></ul><pre>public function run($job, $arguments)<br>{<br>    if ($arguments instanceof Request) {<br>       $result = $this-&gt;dispatchFrom($job, $arguments, $extra);<br>    } else {<br>       $result = $this-&gt;dispatchFromArray($job, $arguments);<br>    }</pre><pre>    return $result;<br>}</pre><ul><li>Run a <em>$job</em> with the given <em>$arguments</em> and when $<em>arguments</em> is an instance of <em>Illuminate\Http\Request </em>Laravel has a special treatment for it by expanding the request’s input parameters into constructor arguments when initialising the job.</li></ul><p>Now all we have to do is define the jobs that implement the feature.</p><h4>Jobs</h4><p>Laravel has crafted some magic that makes it easy for us to dispatch jobs so all we have to do is implement a method called <em>handle</em> on every feature and job so that Laravel takes care of the initialisation process, you may also inject your dependencies in <em>handle</em> and they will be automatically resolved.</p><p>In order to register a citizen we need their name, email, social security number, occupation and address, which leads us to validating the input data.</p><p>Here’s the list of jobs that accomplishes our feature:</p><ul><li><strong>validate</strong> agent input of citizen data for their correct format</li><li><strong>register</strong> citizen</li><li><strong>notify </strong>officers</li></ul><p>Let’s add these jobs to our feature class:<br><em>src/Services/Site/Features/RegisterCitizenFeature.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d595c89d7558c8d5b11f9fc06e20dccc/href">https://medium.com/media/d595c89d7558c8d5b11f9fc06e20dccc/href</a></iframe><blockquote>You may wish to create a foundational <em>Request</em> class extending <em>Illuminate\Http\Request</em> which is the recommended way to go about it but for the sake of the example we will not do that.</blockquote><p>The jobs mentioned above introduces two domains:</p><ul><li><strong>Citizen:</strong> Responsible for our citizen-related jobs such as validating registration input and registering citizens.</li><li><strong>Notification:</strong> A place for all the possible notifications in our system. We could’ve added a <strong>Notifications</strong> folder inside the <strong>Citizen</strong> domain but that will make it harder for us to “list” all the notifications that we can listen to across the application, and their different ways of being broadcasted. i.e. an email notification, web notification, mobile push notification etc.</li></ul><p>In <em>src/Domains/Citizen/CitizenCreationValidator.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27f6e594b2439c74d4cb27a5f90e7ddb/href">https://medium.com/media/27f6e594b2439c74d4cb27a5f90e7ddb/href</a></iframe><p>And our base validator looks like this:<br><em>src/Foundation/Validator.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a9d1e026155d63b1b22a766f6adafa6/href">https://medium.com/media/2a9d1e026155d63b1b22a766f6adafa6/href</a></iframe><p><em>src/Foundation/Validation.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b7339fe945da68b1627d7003839a5e8/href">https://medium.com/media/7b7339fe945da68b1627d7003839a5e8/href</a></iframe><p><em>src/Foundation/InvalidInputException.php</em></p><p>Our exception class is a bit special since it can accept a Validator as a message where it extracts the messages from it, as well as an array of messages (as strings).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dd3b9921ca5247764f8f58bcc9735a5/href">https://medium.com/media/8dd3b9921ca5247764f8f58bcc9735a5/href</a></iframe><p>Our <em>Validator</em> class throws an <em>InvalidInputException</em> when validation fails according to the <em>$rules</em> property, <em>InvalidInputException</em> supports a <em>Validator</em> instance as a message and will extract the messages from it accordingly, as well as accepting an array of messages.</p><p>We will get back to implementing the rest of the jobs right after we introduce our Entities needed by these jobs.</p><h4>Models</h4><p>We value <a href="http://web.eecs.utk.edu/~mclennan/papers/VOPL.ps"><em>Value Objects</em></a> (see what I did there? 😉) and encourage their use when possible, or you know what? All the time! One convention to follow is way better than asking whether it should be a value object or not, so moving forward expect every property of a model to be a value object.</p><blockquote>Value Objects MUST be immutable and are self-validating</blockquote><p>Having <em>Value Objects </em>self-validating eliminates the hassle of heavy validators and rules scattered all over the place, they’re now in one place and that places is the object itself. Which makes our validation job very easy: check for the existence of the required input fields, the rest is handled by the values (format validation, post-formatting, etc.).</p><p>How do we use value objects, you ask? In our case it will be every citizen’s property like <em>name, email, etc. </em>We call them <strong>Values</strong> so we will create a foundational Value providing a basic immutable object structure to be inherited by model values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4f90c736a0690c29abde827acdc99f3/href">https://medium.com/media/a4f90c736a0690c29abde827acdc99f3/href</a></iframe><p>Now we create our citizen values extending this one. For simplicity we won’t be delving into all of the values, instead we will give an example of how they might operate.</p><blockquote>Feel free to replace “Entities” with “Models”, some people prefer to do so.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0e75258598fd5f19ca89064a9b45b5e/href">https://medium.com/media/b0e75258598fd5f19ca89064a9b45b5e/href</a></iframe><p><em>src/Data/Entities/Citizen/Values/Email.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1950f6aea16e6691f5ab57aa3dad47ae/href">https://medium.com/media/1950f6aea16e6691f5ab57aa3dad47ae/href</a></iframe><p>It is not necessary for every value to be as large as this one, in fact they will rarely do except when there’s business rules involved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*FBdceTODt10EDgRlffnVGA.png" /></figure><p>We end up with a structure similar to this one.</p><p>Last but not least our <strong><em>Citizen </em></strong>and its repository:<br><em>src/Data/Entities/Citizen/Citizen.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d96bdd81799bb27f239016e008e4d82/href">https://medium.com/media/1d96bdd81799bb27f239016e008e4d82/href</a></iframe><blockquote>Working with models may require a little database configuration on your side but it is outside the scope of this example.</blockquote><p><em>src/Data/Repositories/CitizenRepository.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46371a85ba35c5eb4b29f316182c15d2/href">https://medium.com/media/46371a85ba35c5eb4b29f316182c15d2/href</a></iframe><p>Our <em>AbstractRepository </em>is still empty but in a real life scenario we’d have lots of common functions such as <em>find, findByX, all, remove </em>and many more..<em>.</em></p><blockquote>Remember to add a method to your AbstractRepository that sets the entity as a property to be used for querying.</blockquote><blockquote>We use repositories as our exclusive access to entities,</blockquote><blockquote><strong>direct access to entities is not encouraged whatsoever</strong>.</blockquote><p>This is how our directory structure looks like by now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*oWQBQLEzlEWvKS5WNj_VTQ.png" /></figure><blockquote>By just looking at it you can start picturing the components that make up our project, and their relations (somehow)</blockquote><p>This structure can answer questions such as:</p><ul><li><strong>Q:</strong> What are the features implemented in <em>Site.<br></em><strong><em>A:</em></strong><em> RegisterCitizenJob, ValidateCitizenCreationJob</em></li><li><strong>Q:</strong> What are the entities, their values and the exceptions they throw.<br><strong><em>A:</em></strong><em> Entitys: Citizen -&gt; Values: Name, Email, etc.</em></li><li><strong>Q:</strong> What jobs does the X domain implement — what are the possible processes that I can perform using this domain.<br><strong><em>A:</em></strong><em> Citizen::RegisterCitizenJob</em></li></ul><h4>Back To Jobs</h4><p>Let’s start with the usual: a foundational <em>AbstractJob</em> to be extended by jobs.<br>In <em>src/Foundation/AbstractJob.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7e05a6e8cb3a00c5c785927fb4dd424/href">https://medium.com/media/c7e05a6e8cb3a00c5c785927fb4dd424/href</a></iframe><p>In <em>src/Domains/Citizen/Jobs/ValidateCitizenCreationInputJob.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19cd1deecc2ff2290c1ecbcd05ae971e/href">https://medium.com/media/19cd1deecc2ff2290c1ecbcd05ae971e/href</a></iframe><p>As you see the implementation of a Job is straight forward, implement the <em>handle()</em> method declaring your dependencies to be injected and return the results of “handling” the job.</p><p><em>src/Domains/Citizen/Jobs/RegisterCitizenJob.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fd9f251f11e373d08cb6a8f98752cf1/href">https://medium.com/media/5fd9f251f11e373d08cb6a8f98752cf1/href</a></iframe><p>Our last job <em>NotifyOfficersJob </em>is a different kind of job, let me tell you why:</p><p>Events such as notifications are (usually) treated in an async way so that they don’t block execution, mainly because they’re used with a queue of notifications that are dispatched one after the other when the time is right, which means we might have to wait a little while for another notification to finish propagating. We don’t want our execution to halt during the process, hence a <em>Queueable Job.</em></p><p>Let’s start with creating our foundational Queueable job:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1794128813730ffd6d9faf6f92818a95/href">https://medium.com/media/1794128813730ffd6d9faf6f92818a95/href</a></iframe><p>Any job extending <em>AbstractQueueableJob</em> will automatically be dispatched into a queue and ran when possible, which brings us to Queues. Similar to <em>Notifications, Queues</em> will have their own domain for centralisation purposes.</p><p>Start by creating the domain and a <em>DefaultQueue<br></em>In <em>src/Domains/Queue/AbstractQueue.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eb509b1c1a2d8d3dbe8b56681901428/href">https://medium.com/media/8eb509b1c1a2d8d3dbe8b56681901428/href</a></iframe><p><em>src/Domains/Queue/DefaultQueue</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5da6bd64f579182a28fa694952688e1f/href">https://medium.com/media/5da6bd64f579182a28fa694952688e1f/href</a></iframe><p>Now we need a method in our <em>AbstractFeature </em>that works with queues:<br>In <em>src/Foundation/Feature.php, hence </em><strong><em>runInQueue</em></strong><em>:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29d783c32374d058ce4b6395a792120c/href">https://medium.com/media/29d783c32374d058ce4b6395a792120c/href</a></iframe><p>What this does is assign a default queue if none specified then create an instance of the assigned Job passing the given <em>$arguments</em> and dispatch it into the queue.</p><p>This requires that we change the call to <em>NotifyOfficersJob</em> in our feature class <em>RegisterCitizenFeature</em> to the following:</p><pre>$this-&gt;runInQueue(NotifyOfficersJob::class, [‘notification’ =&gt; new CitizenCreatedNotification($citizen)]);</pre><p>Sending a web-based notification is the matter of firing an event according to Laravel so we’ll do that and whoever is listening to our event will have the notification for them to tinker with.<br>In <em>src/Domains/Notification/Jobs/NotifyOfficersJob.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2a33f7d03f467b169ca514527090bd4/href">https://medium.com/media/a2a33f7d03f467b169ca514527090bd4/href</a></iframe><p>The notification we’re dispatching is in <em>src/Domains/Notification/Notifications/CitizenCreatedNotification.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f67cebdf91c6bf78dfbc214c4753ee4/href">https://medium.com/media/0f67cebdf91c6bf78dfbc214c4753ee4/href</a></iframe><p>You may lift that up a notch and go deeper using <a href="http://laravel.com/docs/5.1/events#broadcasting-events">Broadcasting</a> but we will not delve into this for the sake of simplicity.</p><blockquote>Notifications may grow overwhelmingly in number so you might consider separating them into corresponding folders under Domains/Notification/Notifications/*</blockquote><h4>Testing</h4><p>We’ve been writing a lot of code and we haven’t tested if any of that is actually working. This is not the ideal way of writing code, you most probably will be following some sort of an xDD (Tdd, Bdd, etc.) workflow but for the sake of the example we won’t go through any of them, we will use PHPUnit to test our Site’s features.</p><ul><li>Create the tests directory in <em>src/Services/Site/Tests/Features</em></li><li>Configure PHPUnit to read our tests from inside the Site service by adding the following snippet to <em>phpunit.xml</em></li></ul><pre>&lt;phpunit&gt;<br><br>  &lt;testsuites&gt;<br>     ...</pre><pre>     &lt;testsuite name=”Site Service Features Test Suite”&gt;<br>       &lt;directory&gt;./src/Services/Site/Tests/Features/&lt;/directory&gt;<br>     &lt;/testsuite&gt;</pre><pre>  &lt;/testsuites&gt;</pre><pre>...<br>&lt;/phpunit&gt;</pre><p>And it should look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4fd77a18042b3cb479a6bc53ec06345/href">https://medium.com/media/d4fd77a18042b3cb479a6bc53ec06345/href</a></iframe><ul><li>Create the foundational test case class in <em>src/Foundation/TestCase.php</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94ce1f0286a0525fa11f116d3bbc12e2/href">https://medium.com/media/94ce1f0286a0525fa11f116d3bbc12e2/href</a></iframe><blockquote>By extending Laravel’s <em>TestCase </em>we gain the capabilities provided by the framework listed in <a href="http://laravel.com/docs/5.1/testing#application-testing">the docs</a>.</blockquote><ul><li>Now we test the feature in <em>src/Services/Site/Tests/RegisterCitizenFeatureTest.php</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9bfbb8c7383156d16a8201d9e28ee6a/href">https://medium.com/media/f9bfbb8c7383156d16a8201d9e28ee6a/href</a></iframe><p>For our tests to run we need to return a proper response from our feature class so let’s do that now.</p><p>Since features’ responsibilities are exclusive to running jobs it is necessary for us to have a “responder” job, something like <em>RespondWithJsonJob</em> and the best domain I can think of for such job is an <em>Http</em> domain.<br>In<em> src/Domains/Http/Jobs/RespondWithJsonJob.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cebd06b30e491a98d37ab9f9dfbe0ba/href">https://medium.com/media/0cebd06b30e491a98d37ab9f9dfbe0ba/href</a></iframe><p>Now if we run our tests we should get all green!</p><pre>./vendor/bin/phpunit</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ZDaKUWEEfT4HBtDDkEE_fg.png" /></figure><blockquote>Wondering why it shows 2 tests instead of 1? It’s because of Laravel’s <em>ExampleTest.</em></blockquote><p>If you want a more fun way of implementing your feature tests you should checkout <a href="http://behat.org/">Behat</a>. Here’s a post to get you started:</p><p><a href="https://medium.com/p/949156a37e66">Building Reliable APIs using BDD — Behat &amp; Laravel 5 (Part 1)</a></p><p>You can find the code of this blog post on <a href="https://github.com/Vinelab/lucid-architecture-php">Github</a>.<br>Please contribute your thoughts, implementation or whatever you see beneficial.</p><blockquote><em>we’d love your feedback,</em></blockquote><blockquote>Happy Coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be99abd108cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vinelab-tech/the-lucid-arhitecture-implementation-be99abd108cf">The Lucid Architecture — Implementation</a> was originally published in <a href="https://medium.com/vinelab-tech">Vinelab · Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Lucid Architecture — Concept]]></title>
            <link>https://medium.com/vinelab-tech/the-lucid-architecture-concept-ad8e9ed0258f?source=rss-1ea6c1a3d2fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad8e9ed0258f</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[tehnology]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Abed Halawi]]></dc:creator>
            <pubDate>Tue, 28 Jul 2015 10:25:14 GMT</pubDate>
            <atom:updated>2020-12-15T19:29:16.127Z</atom:updated>
            <content:encoded><![CDATA[<p>A modern look at how we architect software for scale.</p><blockquote>To amuse your lucid mind and stimulate it creatively.</blockquote><p><strong>Update 15–05–2020:</strong> After 5 years passing since the announcement of Lucid, and due to the demand and adoption of this architecture, it has become essential to have a standalone place for proper documentation and resources. And it’s finally <a href="https://docs.lucidarch.dev/">here</a>! Check it out for the up-to-date information and <a href="http://lucid-slack.herokuapp.com/">join the community</a>. Also, <a href="https://lucidarch.dev/">the website</a> lays out the benefits of using an architecture.</p><p>Nevertheless, the below is the inception of the concept and it hasn’t changed ever since. In fact, it has only evolved.</p><p>The good news is that we’ve been using it ever since, and it has proven to be reliable and saved us a huge amount of tech dept. I hope it does the same to you too.</p><p>Check it out on <a href="https://github.com/lucidarch/lucid">GitHub</a>.</p><h4>The Argument</h4><p>Developing large-scale applications has always been easy to think about but when it comes to implementaiton lots of questions arise especially when working in a collaborative team where every decision is peer-discussed and made over coffee or beer on a napkin, some of these discussions go around subjects such as:</p><ul><li>Where should this good piece of art code reside (folder, file, class, etc.)?</li><li>What design patterns should we apply to implement this feature?</li><li>How can you describe the underlying architecture that is running…EVERYTHING!?</li></ul><p>If I’m hearing you correctly you’re saying <a href="http://www.slideshare.net/igortalevski1/laravel-5-and-solid">SOLID</a> using Repository pattern, Factories and Value Objects all living inside their corresponding domain and that’s totally true but it’s the wrong answer to these questions for this is more about the structure and architecture rather than the concrete implementation. Which brings us to the necessity for a guideline to protect the application’s dignity.</p><h4>The Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7mK5t3qoa-5ODxRpAhdrA.jpeg" /><figcaption>The Lucid Architecture</figcaption></figure><ul><li><strong>Framework</strong> provides the “kernel”, request/response lifecycle, dependency injection and the core functionalities for the Foundation to build on. Knows nothing about the application logic.</li><li><strong>Foundation</strong> provides support to the concrete components of the architecture (services, domains and data) by extending the framework with fundamental (abstract) classes; due to that, and the fact that the concrete components will only deal with the foundation, any change at the framework level will be transparent and have the least effect possible on the application overall and as a result <strong>the Lucid architecture grants a reduced amount of </strong><a href="https://en.wikipedia.org/wiki/Technical_debt"><strong>technical debt</strong></a><strong> in the case of a drastic update/upgrade or even migration to another framework</strong>.</li></ul><blockquote>Examples of what the foundation might include:</blockquote><blockquote><em>- FoundationController</em> to be extended by services’ controllers</blockquote><blockquote><em>- Entity</em> class that extends <em>the ORM’s entity/model or any kind of base model</em></blockquote><blockquote>Abstract Feature and Job classes</blockquote><blockquote>Decorators for validation, authentication etc.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*hGpnzRbadSmpoVVbM83PIA.png" /></figure><ul><li><strong>Services</strong> implement the <strong>features</strong> but do not implement the logic of the feature themselves, their responsibility is to communicate with domains by dispatching their <strong>jobs</strong> and <strong>operations</strong>. Think of a job as a step if the feature was a <a href="https://en.wikipedia.org/wiki/Use_case">use-case</a>; an operation is a group of steps that are often executed together though they operate the same as a feature — dispatch jobs.</li></ul><blockquote><strong>Services Example:</strong> a project consisting of an API and a Back Office where you would implement each in its own scope yet share a lot between them. Hence <strong>Domains </strong>and <strong>Data</strong>.</blockquote><blockquote>The terminology of a service is used in the form of “Our application provides data through an API service, it also has a Back Office service to perform advanced data manipulation procedures.</blockquote><ul><li><strong>Domains </strong>implement the business logic and expose them through jobs, they are isolated and MUST NOT inter-communicate.</li></ul><blockquote><strong>Domains Example:</strong> in a task management app there’s the <em>User</em> domain and <em>Task</em> domain each having its own validators, generators, builders, factories, utility classes etc. and they utilise the data layer to perform data-specific procedures in addition to Jobs that are (favourably) the only way to communicate with domains. Potential Jobs in a task management app in the <em>Task </em>domain could be: <em>AddTaskJob, MarkTaskAsCompletedJob, AssignTaskToUserJob</em></blockquote><blockquote>We suffix Job classnames with “Job” for readability and navigation, also extending the PSR-2 coding standard of suffixing interfaces with “Interface” and traits with “Trait”</blockquote><ul><li><strong>Data </strong>owns the data (duh!), which means models (entities) and repositories. You may be asking why separate the data layer from the domains layer? aren’t they related? The answer is of course they are, yet domains remain to be isolate, self-satisfied and no cross-domain relationships exist while data is organically related; if we included them in domains we would’ve ended up working with cross-domain dependencies which defies the idea of domains being self-contained.<br>Another reason for having a separate data layer is the trend of the 21st centry: 💫<strong>data science</strong>✨ which makes this layer the place for your <strong>statistics and analytics algorithms</strong>, a central layer for data manipulation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*h4JqBDvzdtSIPejK55X48A.jpeg" /></figure><blockquote><strong>Domains</strong>, <strong>Jobs</strong> and <strong>Operations</strong> are isolated classes with single responsibilities, they perform one thing and one thing only;</blockquote><blockquote><strong>no inter-domain, inter-job or inter-operation dependencies should exist</strong> <strong>whatsoever</strong>.</blockquote><h3>Benefits</h3><p>Why bother with all this fuss if we could just reside everything in one place? The Framework.</p><h4>Deployment — Infrastructure</h4><p>When deploying large-scale applications the least we have is a bunch of servers running different services of our application, here’s a humble example of what it would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwDW1IwcVted94siancGMA.jpeg" /></figure><p>As you see in the figure above, our application consists of an API, Back Office and a Web App, each having its own infrastructure dependencies yet <strong>sharing Data</strong> and very likely to do so with business rules (<strong>Domains) </strong>on a logical level. For that reason our services declare their own dependencies in their own scope and our architecture strives to support such deployment design by providing the capability of dissecting our large application into small deployable services yet harnessing the power of shared data and logic. I know you may be thinking that this sounds a lot like microservices and yes it could be but that’s not the main purpose, even more our <strong>Services</strong> could be decoupled into several microservices if need be.</p><h4>Organisation— Code Maintenance &amp; Versioning</h4><ul><li>Predictable impact of changes on the system when reviewing code.</li><li>Reduced debugging time since we’re dividing our application into isolated areas of focus (divide and conquer).</li><li>Steep learning curve for new devs/contributors joining aboard, Lucid aims to make their learning journey slightly easier by making it clear where to look for what they need without having to ask their mentors for buried code somewhere for a reason.</li><li>Each of our services can have its own versioning system, i.e. our API is at <em>v1</em> while our Back Office is at <em>v2.3</em>.</li></ul><blockquote>This surely requires some configuration artistry but it is doable in most web programming languages i.e. <a href="http://getcomposer.org/">Composer for PHP</a>, <a href="https://rubygems.org/">RubyGems for Ruby</a>, <a href="http://ant.apache.org/">Ant</a>, <a href="https://maven.apache.org/">Maven</a> and <a href="https://gradle.org/">Gradle</a> for Java, you name it…</blockquote><h4>Reusability — Lucid ♡ Sharing</h4><p>Data and Domains are shared across services for this reason, as well as the Foundation providing common functionalities to encourage reusability whenever possible.</p><h4>Boundaries</h4><p>It is always a good practice to set boundaries as the team grows and the application becomes unbearably large you don’t want to leave room for future code to their fate or destiny wherever they reside, <a href="https://en.wikipedia.org/wiki/Technical_debt">technical debt</a> pays off with bugs and waking you up in the middle of the night for a service outage; coding does not rely on good intentions nor wishes.</p><h3><strong>Closing</strong></h3><p>Looking forward to knowing your opinion so please leave a note of your thoughts.</p><blockquote>Stay tuned for the post where we implement this architecture in an example.</blockquote><p><strong>Update: The implementation has been published, find it here and let us know your feedback.</strong></p><p><a href="https://blog.vinelab.net/the-lucid-arhitecture-implementation-be99abd108cf#.pbz67k90q">https://blog.vinelab.net/the-lucid-arhitecture-implementation-be99abd108cf#.pbz67k90q</a></p><h4>Influences &amp; Resources</h4><p>Just like everything else in life, this architecture was a matter of evolution from a collection of ideas collected from great minds in the tech industry; here’s a shortlist of the sources that influenced this idea:</p><ul><li><a href="http://geekswithblogs.net/theArchitectsNapkin/archive/2015/04/29/the-ioda-architecture.aspx#fnref:2">The IODA Architecture</a></li><li><a href="http://martinfowler.com/tags/domain%20driven%20design.html">Domain-Driven Design — Martin Folwer</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZJ63ltuwMaE%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZJ63ltuwMaE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZJ63ltuwMaE%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bb7be651400a2797e09922928ac1649/href">https://medium.com/media/3bb7be651400a2797e09922928ac1649/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlE6Hxz4yomA%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlE6Hxz4yomA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlE6Hxz4yomA%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/43b4766f8b845a3d823687eda9d24428/href">https://medium.com/media/43b4766f8b845a3d823687eda9d24428/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad8e9ed0258f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vinelab-tech/the-lucid-architecture-concept-ad8e9ed0258f">The Lucid Architecture — Concept</a> was originally published in <a href="https://medium.com/vinelab-tech">Vinelab · Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Reliable APIs using BDD — Behat & Laravel 5 (Part 1)]]></title>
            <link>https://medium.com/vinelab-tech/building-reliable-apis-using-bdd-behant-laravel-5-949156a37e66?source=rss-1ea6c1a3d2fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/949156a37e66</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[behat]]></category>
            <dc:creator><![CDATA[Abed Halawi]]></dc:creator>
            <pubDate>Mon, 13 Jul 2015 10:48:29 GMT</pubDate>
            <atom:updated>2015-07-13T10:53:48.061Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Reliable APIs using BDD (Behaviour-Driven Development) in PHP — Behat &amp; Laravel 5 (Part 1)</h3><h4>Why</h4><p>It has been known lately that BDD is a favourable testing approach especially when it comes to building APIs, be it a public API for a variety of client implementations (mobile apps, websites or 3rd party consumers) or using microservices, in both cases the API is the backbone that your data flow relies on so the more robust it is the more reliable it will be which brings us to testing.</p><p>If you are asking why Behat? I am sure you’ve looked that up multiple times and found numerous readings about it but I will have to credit my decision to Robert C. Martin or more commonly known as <a href="https://www.google.com/search?client=safari&amp;rls=en&amp;q=uncle+bob&amp;ie=UTF-8&amp;oe=UTF-8">Uncle Bob</a> who said in <a href="https://sites.google.com/site/unclebobconsultingllc/the-truth-about-bdd">The Truth about BDD</a>:</p><blockquote>It connects the human concept of cause and effect, to the software concept of input/process/output.</blockquote><p>In addition to comparing it to a way to describe the finite state machine which is how I often find myself understanding software.</p><h4>What</h4><p>We will be building a sample API using Behat 3.x and Laravel 5.1.</p><h4>How (Code Please)</h4><h4>Installation</h4><p>Let’s start with a fresh Laravel 5.1 installation</p><pre>composer create-project laravel/laravel behat-l5-apis ~5.1</pre><p>Next we will add Behat to our development requirements</p><pre>composer require --dev behat/behat 3.0</pre><p>After this step we should have <em>vendor/bin/behat</em> there and ready for our commads.</p><blockquote>It is handy to add ./vendor/bin to your PATH so that you can call commands without mentioning their full path.</blockquote><pre>export PATH=$PATH:./vendor/bin</pre><p>Remember to reload your terminal session for the changes to take effect.</p><p>If you’re not familiar with the Gherkin syntax (it’s the English your write that magically translates into machine language) it’s fairly simple and no, nothing is magical about it and you will realise that as you read along.</p><p>It’s about Features and Scenarios. A feature is obviously the feature we’re testing and it is composed of scenarios, think of them as the possible ways the user could be interacting with this feature. Here’s an example:</p><pre><strong>Feature: </strong>Building Cars<br>    In order to facilitate human transportation<br>    As a manufacturer<br>    I need to build them fancy cars</pre><pre>    <strong>Scenario:</strong> Build a regular 4-seater vehicle<br>        <strong>Given</strong> I want to build a car named &quot;Reek&quot;<br>        <strong>And </strong>I have 4 doors<br>        <strong>And</strong> I have 4 wheels<br>        <strong>And</strong> the colour is &quot;blue&quot;<br>        <strong>And</strong> the engine has the power of 600 horses<br>        <strong>When</strong> I build the car<br>        <strong>Then</strong> I should get:<br>        &quot;&quot;&quot;<br>        {<br>            &quot;status&quot;: &quot;success&quot;,<br>            &quot;time&quot;: &quot;2 days&quot;<br>        }<br>        &quot;&quot;&quot;</pre><p>For more details about the language visit <a href="http://behat.readthedocs.org/en/v2.5/guides/1.gherkin.html#gherkin-syntax">Writing Features — Gherkin Language</a>.</p><h4>Configuration</h4><p>We need to tell Behat how to locate our tests, the configuration is in YAML.</p><p>Create a file called <em>behat.yml</em><strong> </strong>at the root of the project with this content:</p><pre>default:<br>    suites:<br>        api:<br>            paths: [tests/Api/features]<br>            contexts: [App\Tests\Api\ApiFeatureContext]</pre><p>What this basically says is: “Behat, I have a group of features for the API that I’d like to have them loaded from <em>tests/Api/features</em> and use <em>ApiFeatureContext</em> as my context class”. What is a context class you ask? you’ll know in a bit.</p><p>Now we go ahead and create the latter.</p><pre>tests/Api/features <strong>&lt;&lt;&lt; This is our features directory</strong><br>tests/Api/ApiFeatureContext.php <strong>&lt;&lt;&lt; This is our context class</strong></pre><p>The context class <em>ApiFeatureContext </em>is the class that will have the definitions of sentences such as “<strong>Given</strong> I <em>bla bla bla…</em>” and to do that the content of that file should be:</p><pre>&lt;?php</pre><pre>namespace App\Tests\Api;</pre><pre>use Behat\Behat\Context\Context;<br>use Behat\Behat\Context\SnippetAcceptingContext;</pre><pre>class ApiFeatureContext implements Context, SnippetAcceptingContext</pre><pre>{</pre><pre>}</pre><p>Before we test the waters we need to ask composer to autoload our test classes using PSR-4. In <em>composer.json</em> at the <em>autoload</em> section we modify <em>psr-4</em> with the following:</p><pre>“psr-4”: {</pre><pre>    “App\\”: “app/”,<br>    “App\\Tests\\”: “tests/”</pre><pre>}</pre><p>Reload your classes with</p><pre>composer dump-autoload</pre><p>Now we’re good to go, if you run <em>behat</em> you should get this:</p><pre>&gt; behat</pre><pre>No scenarios<br>No steps<br>0m0.00s (10.29Mb)</pre><p><strong>Hurray!</strong></p><h4>Setup</h4><p>As you may know Laravel ships with a handy of <a href="http://laravel.com/docs/5.1/testing">assertions and crawler methods</a> that are extremely useful for testing such as:</p><pre>$this-&gt;visit(‘/’)<br>    -&gt;see(&#39;Laravel 5&#39;);</pre><pre>$this-&gt;post(&#39;/user&#39;, [&#39;name&#39; =&gt; &#39;Sally&#39;])<br>    -&gt;seeJson([<br>        &#39;created&#39; =&gt; true,<br>    ]);</pre><p>I hear you “we want those too!” so let’s have them available for us in our <a href="http://docs.behat.org/en/v2.5/quick_intro.html#the-context-class-featurecontext">Context class</a> before diving into the implementation.</p><p>We will create a “base” feature context calling it <em>LaravelFeatureContext</em> which can be extended if need be.</p><p>In <em>tests/LaravelFeatureContext.php</em></p><pre>&lt;?php</pre><pre>namespace App\Tests;</pre><pre>use TestCase;<br>use Behat\Behat\Context\Context;<br>use Behat\Behat\Context\SnippetAcceptingContext;</pre><pre>class LaravelFeatureContext extends TestCase implements Context, SnippetAcceptingContext</pre><pre>{</pre><pre>}</pre><p>Now that our beloved <em>LaraveFeatureContext</em> class is implementing <em>Context </em>and <em>SnippetAcceptingContext</em> we won’t have to in our child context classes so our <em>ApiFeatureContext</em> will look like this</p><pre>&lt;?php</pre><pre>namespace App\Tests\Api;</pre><pre>use App\Tests\LaravelFeatureContext;</pre><pre>class ApiFeatureContext extends LaravelFeatureContext</pre><pre>{</pre><pre>}</pre><h4>Implementation</h4><p>Let’s start writing our first feature test. We will begin using our previous feature example.</p><p>In <em>tests/Api/features/building-cars.feature</em></p><pre><strong>Feature: </strong>Building Cars<br>    In order to facilitate human transportation<br>    As a manufacturer<br>    I need to build them fancy cars</pre><pre><strong>Scenario:</strong> Build a regular 4-seater vehicle<br>        <strong>Given</strong> I want to build a car named &quot;Reek&quot;<br>        <strong>And </strong>I have 4 doors<br>        <strong>And</strong> I have 4 wheels<br>        <strong>And</strong> the colour is &quot;blue&quot;<br>        <strong>And</strong> the engine has the power of 600 horses<br>        <strong>When</strong> I build the car<br>        <strong>Then</strong> I should get:<br>        &quot;&quot;&quot;<br>        {<br>            &quot;status&quot;: &quot;success&quot;,<br>            &quot;time&quot;: &quot;2 days&quot;<br>        }<br>        &quot;&quot;&quot;</pre><p>Now we need to ask Behat to kindly generate the required context methods in our context class by running:</p><pre>behat --dry-run --append-snippets</pre><p>The output should look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*759h7MZoWwDRc85gB3oJSA.png" /></figure><p>Now if we take a look at <em>ApiFeatureContext, </em>SURPRISE! The methods that implement the definitions of the Gherkin sentences we just wrote are there for us to implement.</p><p>If we take a look at the first method (as a personal preference I like to rename the arguments from <em>$arg1.. </em>to something more meaningful) it is where we will start building our car:</p><pre>use App\Builders\CarBuilder;</pre><pre>...</pre><pre>protected $carBuilder;</pre><pre>/**<br> * @Given I want to build a car named :name<br> */<br>public function iWantToBuildACarNamed($name)<br>{<br>    $this-&gt;carBuilder = new CarBuilder();<br>    $this-&gt;carBuilder-&gt;setName($name);<br>}</pre><p>Now we need our <em>CarBuilder</em> class, we will be evolving this class as we move on with the tests.</p><p>In <em>app/Builders/CarBuilder.php</em></p><pre>&lt;?php</pre><pre>namespace App\Builders;</pre><pre>class CarBuilder</pre><pre>{<br>    protected $name;</pre><pre>    public function setName($name)</pre><pre>    {<br>        $this-&gt;name = $name;<br>    }</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*U7BPhpkeFdWGTIHWi7UiFQ.png" /></figure><p>Now if we run <em>behat</em> again our first step of the scenario is now green.</p><p>Now we fill the rest of the definitions and implement the corresponding builder methods until we get to build and verify (assert) the response:</p><pre>/**<br> * @When I build the car<br> */<br>public function iBuildTheCar()<br>{<br>    $this-&gt;buildResponse = $this-&gt;carBuilder-&gt;make();<br>}</pre><p>Now we need to assert that the build response was as expected, to do that we will need to use <strong>PHPUnit</strong>’s assertions, PHPUnit is already installed for us by Laravel so all we have to do is import the namespace:</p><pre>use PHPUnit_Framework_Assert as PHPUnit;</pre><p>Now we can use it as <strong>PHPUnit::assertEquals(…)</strong></p><p>Let’s assert our build status was as expected</p><pre>/**<br> * @Then I should get:<br> */<br>public function iShouldGet(PyStringNode $string)<br>{<br>    $expected = json_decode($string, true);<br>    PHPUnit::assertEquals($expected, $this-&gt;buildResponse);<br>}</pre><p>That <strong>PyStringNode</strong> came out of nowhere so we need to import it from Behat’s namespace</p><pre>use Behat\Gherkin\Node\PyStringNode;</pre><p>And <strong>CarBuilder::make()</strong> is just a function lying to us about the build for now:</p><pre>public function make()<br>{<br>    return [<br>        ‘status’ =&gt; ‘success’,<br>        ‘time’ =&gt; ‘2 days’,<br>    ];<br>}</pre><p>If all the methods were implemented and working our tests should all be green as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcmquyaJJmN3GbjGL3xZkw.png" /></figure><h4>Wrap Up</h4><p>Finally, this example’s purpose was to give you an idea about how you could setup Behat and Laravel although we haven’t harnessed the powers that Laravel provides, which is what we’ll do in the next part (part 2).</p><p>Follow me on <a href="https://twitter.com/mulkave">Twitter</a> to know when the next part is out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=949156a37e66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vinelab-tech/building-reliable-apis-using-bdd-behant-laravel-5-949156a37e66">Building Reliable APIs using BDD — Behat &amp; Laravel 5 (Part 1)</a> was originally published in <a href="https://medium.com/vinelab-tech">Vinelab · Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>