<?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 Thiago Cordeiro on Medium]]></title>
        <description><![CDATA[Stories by Thiago Cordeiro on Medium]]></description>
        <link>https://medium.com/@thiagoguetten?source=rss-3752e8d40bf4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ut-1gWQpdPvzIJaU1mjW-w.jpeg</url>
            <title>Stories by Thiago Cordeiro on Medium</title>
            <link>https://medium.com/@thiagoguetten?source=rss-3752e8d40bf4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 20:44:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thiagoguetten/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[Object Encapsulation]]></title>
            <link>https://medium.com/mollie-payments/object-encapsulation-9919a4e96ce1?source=rss-3752e8d40bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9919a4e96ce1</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[rich-entities]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[encapsulation]]></category>
            <dc:creator><![CDATA[Thiago Cordeiro]]></dc:creator>
            <pubDate>Wed, 24 Feb 2021 14:08:31 GMT</pubDate>
            <atom:updated>2021-02-24T14:08:31.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AcsFOeDyXeaOMmjCf1FCpQ.png" /></figure><p>Once upon a time, we had just finished lunch and, as usual, I was heading to prepare a cappuccino at the office coffee machine, running away from Pietro (our Italian mate), I could hear him saying “<em>Hey… you are not allowed to have a cappuccino after 11 am</em>”. Well, this day Albert and Robin were putting on their jackets and Albert invited me to have a coffee outside the office, a slightly different one, made of coconut milk. Of course, I’m always in for a good coffee and joined them, so we went down the stairs and walked around the block to reach the place.</p><p>Once there, we did what we usually do when ordering a coffee, said hi to the barista, Albert ordered his coffee, Robin was next, and finally myself. I tasted and woooow, that’s amazing. I will definitely come back again I thought, we paid, and headed back to the office.</p><p>That’s a normal life story, not very detailed but something like this happens every day and everything goes very smoothly. The process is very simple: put on the jacket, go downstairs, walk to the coffee place, order, be happy, pay, and get back to work, easy to understand as well as easy to repeat, we can do it every day unless we run out of money.</p><p><strong>Let’s change the perspective…</strong></p><p>They invited me, we put on our jackets and headed to the place, then… We arrived there, said hi to the barista, Albert went to the bar, prepared his coffee, Robin was next, and finally myself, prepared, tasted, and the coffee was just amazing. While we enjoyed our coffee the barista picked up our wallets and got the amount to pay for the coffee, put our wallets back in our pockets, we said bye, and went back to the office.</p><p>Same story, our goal was to have a coffee and we achieved it, we had the coffee, we paid, and we got back to work.</p><p><strong>Why does the second sound so weird?</strong></p><p>Because it loses encapsulation: We own the wallet, so it’s our responsibility to take the money and pay. We are a framework, we can do a bunch of different things and we are <em>sometimes </em>mindful of risks, responsibilities and boundaries, so it’s our duty to grab the money and pay. A barista is an external interface, they don’t care how you’ll pay, they just care about receiving the money no matter which card we use, whether it’s debit, credit, or whether we pay by cash. They only care about receiving the amount for the coffee and hopefully some tip.</p><p>Usually, those actions are very clear in our daily life, but are they clear when we write code?</p><p><strong>Let’s write some code:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae75024e2af51b92bea4a25fac0ef40e/href">https://medium.com/media/ae75024e2af51b92bea4a25fac0ef40e/href</a></iframe><p>That could be a normal code in your engineering life and, maybe it’s not obvious, but do you see the issue with structuring your code this way? This is the same as the barista picking up our wallets and taking the money out, but can we guarantee the wallet has enough money and we don’t have to wash dishes? Can we guarantee the right credit card will be chosen? Or is the right amount being charged and are we not paying for a <a href="https://en.wikipedia.org/wiki/Kopi_luwak"><em>kopi luwak</em></a>?</p><p>So we should write our code differently, but first, let’s try to draw a real-life scenario and how it actually happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qido9hzAcPM5Fzl-PLsc_A.png" /></figure><p>Step by step the flow would look like this:</p><ul><li>The customer orders a coffee</li><li>The barista gets the bill summary</li><li>The barista asks the customer for the payment</li><li>The customer grabs his wallet and pays</li><li>The barista deposits the payment into their bank account</li></ul><p>This process is correctly encapsulated, each one has the right responsibility and the chance to have a safe and reliable process is higher.</p><p>Now let’s write some code to represent this process:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc0d053f7851a77b3931dc1249a99102/href">https://medium.com/media/fc0d053f7851a77b3931dc1249a99102/href</a></iframe><p>As we can see in the second example, now the wallet balance is not exposed and it guarantees the right amount is being deducted, also now we have the Customer playing its role, in this way the barista will not have direct access to the wallet, and the customer could have some additional logic in it, for example, transferring money from saving to checking account or running away as fast as possible ¯\_(ツ)_/¯</p><p>Now let’s explore how these encapsulations can make our life better.</p><h3>Better testing, more confidence</h3><p>This approach is known as Rich Model. <a href="https://mdzwigala.medium.com/?source=post_sidebar--------------------------post_sidebar-----------">Marcin Dźwigała</a> describes it in his post <a href="https://mdzwigala.medium.com/encouraging-use-of-a-rich-domain-model-e89ef884012e">Encouraging use of a Rich Domain Model</a>, by explaining the Anemic model:</p><blockquote><strong>Rich Domain Model</strong> is what Object Oriented Programming is most suitable for. As we know, <strong>OOP </strong>helps us, developers, to link behavior (<em>methods</em>) with data (<em>properties</em>) using <strong>classes. </strong>Unfortunately, often Entities end up as adapters for a database with lots of getters and setters modifying private properties with almost no business logic […] instead of implementing business logic where it would fit the most, in the Model […] especially in web applications, all of the business logic goes directly into a controller […] And that is the opposite of a Rich Domain Model, an <strong>Anemic Domain Model</strong>.</blockquote><p>All the business logic is moved to different entities. Services become handlers driving the application, connecting multiple entities, aggregates, and interfaces with external dependencies. Testing these entities and aggregates will become much easier since we just need unit tests, they are faster, easier to change and extend.</p><p>Let’s look closer into this example. At some point we might identify bugs, for instance, PHP has a proper <a href="https://www.php.net/manual/en/book.bc.php">math library</a> that prevents issues with <a href="https://floating-point-gui.de/basic/">floating-point</a>. Once it happens we can get the input value (causing the bug) and extend our testing scenarios with it, of course, the new test will fail. Then we can change the implementation to use the library, the new test will pass and all the other scenarios should pass. We fixed the bug and we are confident that nothing will break.</p><h3>Better understanding</h3><p>Martin Fowler once <a href="https://twitter.com/martinfowler/status/1067179181140844544">said</a>:</p><blockquote>Any fool can <strong>write code</strong> that a computer can understand. Good programmers <strong>write code</strong> that <strong>humans</strong> can understand.</blockquote><p>Classes, method names, and Exceptions try to imitate the real-life actions and expressions, and the real-life scenario is very clear to anyone, even for non-engineers. Besides the process, we follow the <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">Single Responsibility Principle</a> where classes are small and holder their isolated responsibility.</p><p>We also should try to follow the (<a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency Inversion Principle</a>). All the database connection and parsing logic, or all the HTTP call stuff and error handling are not part of the business logic. Those are external implementation and we can put everything behind an interface, which can represent a business action, “<em>deposit the money”</em> for instance.</p><h3>Easy to change</h3><p>Imagine we have implementation details in our classes:</p><ul><li>Albert wants to pay his cappuccino using a credit card, the ChargeHandler must be aware of a credit card payment flow (grab the card, authorize the payment, capture the money) and deal with all its edge cases.</li><li>Robin wants to pay with cash, then the ChargeHandler must be aware of a cash payment flow, (collect the cash, check that it’s not fake, deposit into the cash register, return the change, deposit into the bank account).</li><li>I want to pay with bitcoins (of course), so the ChargeHandler needs to generate an address and wait for the confirmation.</li></ul><p>All these implementation details will make the ChargeHandler a very big class, and they have many more steps than a payment flow requires because each method works differently. Can you imagine what this class would look like? Many ifs and many different possible execution flows, it would just make this class hard to change.</p><p>In the real-world there are different interfaces to handle different payment methods, for a credit card there is the machine, which authorizes and captures the money, for cash, there is the cash register, which opens up so the barista can receive the money and return the change, for bitcoins they will have a bitcoin address. The process is the same: Ask for some money, wait for it and deposit somewhere.</p><p>Our objects don’t need to know about these details, they just need to receive a payment, and we can take advantage of the <a href="https://en.wikipedia.org/wiki/Strategy_pattern">Strategy Pattern</a> to handle different methods. TheChargeHandler will contain only payment receiving logic connecting to this interface. We can very easily change and add new business rules to it, for instance: support multi-currencies, or discount/cashback policy, or we can publish an event and have other handlers listening to it.</p><h3>Conclusion</h3><p>By encapsulating objects we guarantee scope limits, in the example, the Barista interacts with the customer, while only the customer can interact with its wallet. Objects have a valid state from the very beginning, and they are aware of how the state can be changed, in the example we check whether the balance is enough.</p><p>We benefit a lot when testing, we can write unit tests without much set up overhead or mocking, all test cases will be very specific and a few lines of code will cover all possible scenarios.</p><p>Any internal change will not cause much trouble or side effects, because the same input will always return the same output.</p><p>And finally, we will represent our code in a much more real-life approach, AKA as <a href="https://martinfowler.com/tags/domain%20driven%20design.html">DDD</a>, where it reflects situations that can be easily understood by anyone.</p><h3>See Also</h3><ul><li><a href="https://kaldi.nl/winkel/kaldi-amsterdam">Kaldi koffie &amp; thee Amsterdam Herengracht</a></li><li><a href="https://blog.pragmatists.com/domain-driven-design-vs-anemic-model-how-do-they-differ-ffdee9371a86">Domain-Driven Design vs. anemic model. How do they differ?</a></li><li><a href="https://mdzwigala.medium.com/encouraging-use-of-a-rich-domain-model-e89ef884012e">Encouraging use of a Rich Domain Model</a></li><li><a href="https://www.codeproject.com/Articles/768052/Golden-Rules-Of-Good-OOP">10 Golden Rules Of Good OOP</a></li><li><a href="https://martinfowler.com/tags/domain%20driven%20design.html">domain driven design</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsNKKxc4QHqA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsNKKxc4QHqA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsNKKxc4QHqA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6b4080e5c55f59efe121886c2a7ce14/href">https://medium.com/media/e6b4080e5c55f59efe121886c2a7ce14/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpTB0EiLXUC8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpTB0EiLXUC8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpTB0EiLXUC8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/33d8a28b1da9d0f5af9f56f1c44e3970/href">https://medium.com/media/33d8a28b1da9d0f5af9f56f1c44e3970/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9919a4e96ce1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mollie-payments/object-encapsulation-9919a4e96ce1">Object Encapsulation</a> was originally published in <a href="https://medium.com/mollie-payments">Mollie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing better Controllers]]></title>
            <link>https://medium.com/mollie-payments/writing-better-controllers-e9ce5480c669?source=rss-3752e8d40bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9ce5480c669</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[http-controllers]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Thiago Cordeiro]]></dc:creator>
            <pubDate>Wed, 30 Sep 2020 07:41:51 GMT</pubDate>
            <atom:updated>2020-09-30T07:41:51.698Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mvWKnmNgyoCKrvnJ6-XqTA.jpeg" /></figure><p>Controllers are a very important part of our software. In desktop apps, they coordinate the application, receiving, parsing and storing data, they perform the business logic and bidirectionally communicate with the view. However, when it comes to web applications they are the entrypoint, which means they play a different role than in desktop apps. In this post we’ll look at how writing controllers differently will lead our code to be more flexible, readable and easy to change.</p><h3>First things first</h3><p>To better understand how a controller works differently in web apps, we will look at the well-known MVC model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYSqgPcWzlRtGqlagdYf8A.png" /></figure><p>Let’s take a closer look. In a typical request/response application, the response will likely be a view (sometimes controllers respond only with a status code because they are actions, like a DELETE to an API). When the view is rendered, the request is finished, there are no interactions anymore, and any other interaction requires a new request/response cycle to be started.</p><p>In other words, in request/response application we have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PeopuQKx4G9LJapZaekczQ.png" /></figure><p>As we can see, there is no back and forth between view and controller, if the controller supplies the view with everything it needs then the view should never get information from elsewhere. Also, we could easily rename model to domain to decouple it from any database layer that might be used. By renaming it to domain, we allow broader use such as making requests to third parties or acting on multiple entities.</p><h3>So how can we improve our controllers?</h3><p>Basically, controllers have two responsibilities in web applications: parsing an <strong>HTTP</strong> request, and returning an <strong>HTTP</strong> response. Keeping this in mind can guide us when thinking about where to place our code. The following tips can help improve how we structure our code:</p><p><strong>Move logic out of controllers</strong></p><p>Moving validation logic into <a href="https://medium.com/swlh/value-objects-to-the-rescue-28c563ad97c6">value objects</a> and business logic into <a href="https://martinfowler.com/eaaCatalog/serviceLayer.html">services</a> allows us to reuse the code elsewhere. Imagine at some point we decide to process some specific information which is coming from a different input layer, like a queue for example. First, we can reuse all of this without having to refactor, and second, we can offer alternatives for HTTP and implement async and failover processes once the inputted data can be stored to be processed later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41f5f901909421bc214b5a3ef6334e4a/href">https://medium.com/media/41f5f901909421bc214b5a3ef6334e4a/href</a></iframe><p>In this example, we can see that we provide the service layer with a ready-to-use object, all the information is already valid once we check when we initialize these objects.</p><p><strong>Write a different controller for each endpoint</strong></p><p>if a controller handles a GET, it should not handle a POST, if it gets a list, it should not load a specific resource. We might have some additional processing on request/response data, for example, converting json into objects, objects into json, or a domain error into HTTP exceptions, but if the controller has too many endpoints it will become bloated and hard to maintain.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcde4828186c1322458ed16e03128bd2/href">https://medium.com/media/dcde4828186c1322458ed16e03128bd2/href</a></iframe><p><strong>Avoid Inheritance</strong></p><p><em>I’m not saying we should never extend classes</em>, but what we should avoid is a controller extending another controller, which extends another controller and is used by half of the application. Whenever we have to change something on the base class constructor we would have a nightmare fixing all those child classes. Also, a controller will probably end up having more responsibilities than just handling a HTTP request/response for that specific process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cecac36ff3635efa290ee5adcb32665/href">https://medium.com/media/5cecac36ff3635efa290ee5adcb32665/href</a></iframe><p>Imagine a situation where we need to load the user from Redis instead of a PHP session, in this case we have to inject the Redis client in all classes extending <em>UserController</em>, because our application would have a bunch of controllers depending on a user being logged in, and we would have to change all of them.</p><p>Instead, if we create service classes to handle specific logic like this, then we can inject these services into our controllers, like the example bellow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a48c8fda556306fb0b623066396e0c5/href">https://medium.com/media/7a48c8fda556306fb0b623066396e0c5/href</a></iframe><p>In this example we extracted the user loading and the access control to different services, so we can easily inject the Redis client into the <em>UserLoader</em> and that is the only place we have to change, it will be very easy to test and all the other places this logic is used will just work the same.</p><p><strong>Error handling and process flow</strong></p><p>We should finish the request as quickly as possible. For example, during a request cycle there are many different places where we can recognize early that the request will not succeed. As soon as we identify that, we can terminate the process right away, there is no need to perform more work than needed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a8c0eca3660ad822898e409b6c0f225/href">https://medium.com/media/4a8c0eca3660ad822898e409b6c0f225/href</a></iframe><p>The process flow should start with: 1. Request, 2. Validation, 3. Execution and finally end with the 4. Response. The controller will validate the data, while a service layer will validate the resource and execute all the business logic, for example, by checking if the user already exists and decide to register or return an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ulJbWzAztOGWDXDl8ZVCg.png" /></figure><h3>Conclusion</h3><p>Sometimes it’s hard to change things in monoliths, but removing the logic from controllers helps our core domain to be more resilient and ensures that business rules are consistently applied across your codebase. Scaling and decoupling applications will lead us to event driven architectures, which means we will be reusing business logic from non-HTTP requests even more.</p><p>Finally, this way of separating out the logic doesn’t force us to refactor everything first, but we can simply implement it as we go and improve on the design constantly.</p><h3>Going further:</h3><ul><li><a href="https://www.ongraph.com/what-is-mvc-architecture-in-a-web-based-application/">What is MVC Architecture in a Web Based Application? - Ongraph</a></li><li><a href="https://martinfowler.com/bliki/ValueObject.html">bliki: ValueObject</a></li><li><a href="https://martinfowler.com/eaaCatalog/serviceLayer.html">Service Layer</a></li><li><a href="https://www.thinktocode.com/2018/07/05/layered-architecture/">Layered Architecture - Think To Code</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F148989192%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F148989192&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F548077481_640.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="640" height="360" frameborder="0" scrolling="no"><a href="https://medium.com/media/b256e30cbf0df451934560fc0c42c9a8/href">https://medium.com/media/b256e30cbf0df451934560fc0c42c9a8/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwfMtDGfHWpA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwfMtDGfHWpA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwfMtDGfHWpA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b97d17fd61a208660e96769c30727f34/href">https://medium.com/media/b97d17fd61a208660e96769c30727f34/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9ce5480c669" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mollie-payments/writing-better-controllers-e9ce5480c669">Writing better Controllers</a> was originally published in <a href="https://medium.com/mollie-payments">Mollie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why HTTP code matters]]></title>
            <link>https://thiagoguetten.medium.com/why-http-code-matters-b327fb9c9a20?source=rss-3752e8d40bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b327fb9c9a20</guid>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[http-response]]></category>
            <category><![CDATA[http-code]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[http-client]]></category>
            <dc:creator><![CDATA[Thiago Cordeiro]]></dc:creator>
            <pubDate>Tue, 20 Aug 2019 19:54:47 GMT</pubDate>
            <atom:updated>2019-11-11T21:17:54.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xtbzaB2Elv3AQx4GkV4oA.gif" /></figure><p>Many backend developers prefer writing APIs rather than user interfaces (backoffice, websites) and the reason is simple, for us it is easier to deal with computer language than creating user interfaces.</p><p>It is exactly what APIs (Application programming interface) are, it means there is no humans reading the information, instead, some kind of software, a website, a mobile app, another API, etc.</p><p>When HTTP is the chosen protocol for communication, many things can happen when the client (an application requesting the API) makes a request: success, errors or failures. Some additional information may be attached to the response body, but the body might not be there for any unexpected reason, but headers will be there if the client reaches the API.</p><p>The thing is, clients shouldn’t rely on response body to understand what happened, they will first look at response headers and response code, it will explain exactly what happened, from that they will look at response body (if available) to parse the content and check for additional information.</p><p>In years of experience, I have seen many applications returning HTTP codes not reflecting what happened on the server, for example, an invalid request content (400) returning Unprocessed Entity (422) or even an Internal Server Error (500) return ok (200) and body containing error description.</p><p>Below you’ll understand what codes stand for and a few reasons why it’s important to return the correct one to reflect what happened on the server side.</p><p><strong>Response codes define who is responsible for the error/failure</strong></p><p>All the codes are grouped from 1xx to 5xx and each group has a different reason/responsible 1xx will be skipped because servers APIs should not return this kind of code.</p><p><strong>2xx Success</strong>: Everybody is happy (usually what clients expect).</p><p><strong>3xx Redirect</strong>: Let clients know they might take some action on its request in order to be successfully completed now or in the future.</p><p><strong>4xx Client error</strong>: Client is doing something wrong, maybe trying to access a non-existing resource <em>(404 Not Found)</em> or trying to execute an invalid action <em>(400 Bad Request), </em>basically 4xx errors can be fixed by the client, we don’t have to do anything and we have full understanding why the error is happening<em>.</em></p><p><strong>5xx Server Error</strong>: Our application is not behaving as it should, this errors shouldn’t happen and we must fix as soon as possible, the client will not know what is happening, what is wrong or what to do, basically they assume the same call can be done again and it should behave. Usually it this situation even us (the API maintainers) will not know what is actually happening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Y-BHUzdE1AhGNfuM-5-W6Q.png" /></figure><p><strong>The more APIs can handle errors, the more robust it is</strong></p><p>Why? simply because 4xx codes represent errors which APIs can control, for example, imagine a scenario where the API is trying to save into database a phone number coming from the client (HTTP Request), your table has a unique index for phone numbers, the API get the data and try to save, if the entry already exists, then database will throw an exception and API will return <strong><em>500 Internal Server Error.</em></strong> 5xx are server errors and we have to fix it, but it is not the case, the client is trying to save a value which is already saved and they have to fix it, sending a different number or just skipping this request.</p><p>Now imagine the same scenario, but before saving, the API checks if the database has already this value stored, in case it exists, the API should return <strong><em>409 Conflict </em></strong>and<strong> </strong>let them know they are doing something wrong, it’s a conflict, they are trying to store an already stored entry.</p><p><strong>HTTP Clients usually handle errors differently for success and failure cases</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df01fba092755b5024206d27fba8be4b/href">https://medium.com/media/df01fba092755b5024206d27fba8be4b/href</a></iframe><p>The following example shows how <a href="https://github.com/axios/axios">axios</a> handles success and failures responses, all 4xx and 5xx will execute catch block, the error param contains the status code and might additionally contain a body with some additional information.</p><p><strong>Conclusion</strong></p><p>HTTP codes bring meaningful information about response and should be used correctly, the body might not be available and there will not be another way to understand what is wrong. HTTP codes define who will be responsible when errors occur and finally HTTP Clients can handle errors properly.</p><p><strong>See Also</strong></p><p>If you want to go deep on this topic, please check the links bellow</p><ul><li><a href="http://shop.oreilly.com/product/0636920021575.do">REST API Design Rulebook</a></li><li><a href="https://www.restapitutorial.com/httpstatuscodes.html">HTTP Status Codes</a></li><li><a href="https://www.codetinkerer.com/2015/12/04/choosing-an-http-status-code.html">Choosing an HTTP Status Code - Stop Making It Hard</a></li><li><a href="https://tools.ietf.org/html/rfc7231">RFC 7231 - Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content</a></li><li><a href="https://www.whoishostingthis.com/resources/http-status-codes">HTTP Status Codes: Every Possible Code Listed</a></li><li><a href="https://http.cat/">HTTP Cats</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b327fb9c9a20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel multi-email Authentication]]></title>
            <link>https://thiagoguetten.medium.com/laravel-multi-email-authentication-eee1d8f48e98?source=rss-3752e8d40bf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/eee1d8f48e98</guid>
            <category><![CDATA[custom-athentication]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Thiago Cordeiro]]></dc:creator>
            <pubDate>Wed, 21 Mar 2018 07:38:33 GMT</pubDate>
            <atom:updated>2020-06-29T12:00:25.905Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://laravel.com/">Laravel</a> is a handy framework that provide a lot of built-in tools to make our life easier, I mean, we don’t wast time installing and setting up things, so we can spend more time working on our application and delivering faster.</p><p>Laravel <em>make:auth</em> generate a full authentication feature with register, login, password change and views for it, but sometimes we need to allow users to login with different emails, this tutorial will guide you to implement it with Laravel.</p><p>Starting with a brand new Laravel project you’ll need to change some configurations and create some files, after you just need to implement a <em>CRUD </em>for this multi email addresses.</p><p>Let’s start creating a new Laravel project, if you need to setup your env please visit <a href="https://laravel.com/">https://laravel.com</a>.</p><pre>composer create-project --prefer-dist laravel/laravel blog</pre><p>And use Laravel default auth feature and run migrations</p><pre>php artisan make:auth</pre><p>and migrate</p><pre>php artisan migrate</pre><p>Good to go. Now create the migration to store the users addresses</p><pre>php artisan make:migration create_user_emails_table</pre><p>then</p><pre><em>public function </em>up()<br>{<br>    Schema::create(&#39;user_emails&#39;, <em>function </em>(Blueprint $table) {<br>        $table-&gt;increments(&#39;id&#39;);<br>        $table-&gt;string(&#39;email&#39;)-&gt;unique();<br>        $table-&gt;smallInteger(&#39;main&#39;)-&gt;default(0);<br>        $table-&gt;smallInteger(&#39;verified&#39;)-&gt;default(0);<br>        $table-&gt;string(&#39;token&#39;)-&gt;nullable();<br>        $table-&gt;integer(&#39;user_id&#39;)-&gt;unsigned();<br>        $table-&gt;timestamps();<br><br>        $table-&gt;foreign(&#39;user_id&#39;)-&gt;references(&#39;id&#39;)-&gt;on(&#39;users&#39;);<br>    });<br>}</pre><p>And a model for this table</p><pre>php artisan make:model UserEmail</pre><p>and <em>$fillable</em> fields</p><pre><em>class </em>UserEmail <em>extends </em>Model<br>{<br>    <em>protected </em>$fillable = [<br>        &#39;email&#39;,<br>        &#39;main&#39;,<br>        &#39;verified&#39;,<br>        &#39;user_id&#39;,<br>        &#39;token&#39;,<br>    ];<br>}</pre><p>In the end you create a migration to remove old email column on users table, but<strong> attention, </strong>if you are changing a running application don’t forget to migrate emails from <em>users</em> to <em>user_emails</em> table</p><pre>php artisan make:migration remove_email_column</pre><p>drop the column</p><pre><em>public function </em>up()<br>{<br>    Schema::table(&#39;users&#39;, <em>function </em>(Blueprint $table) {<br>        $table-&gt;dropColumn(&#39;email&#39;);<br>    });<br>}</pre><p>migrate</p><pre>php artisan migrate</pre><p>Laravel default authentication provider find user by email on users table, let’s extend it to check emails on our new table</p><pre>php artisan make:provider MultiEmailAuthentication</pre><p>We don’t want to write a complete new auth provider, so let’s extend it and remove <em>boot</em> and <em>register</em> methods because <em>EloquentUserProvider </em>already have it, also we need to override <em>retrieveByCredentials </em>method to check users on the new table:</p><pre><em>namespace </em>App\Providers;<br><br><em>use </em>App\User;<br><em>use </em>App\UserEmail;<br><em>use </em>Illuminate\Auth\EloquentUserProvider;<br><em>use </em>Illuminate\Contracts\Auth\Authenticatable;<br><br><em>class </em>MultiEmailAuthentication <em>extends </em>EloquentUserProvider<br>{<br>    <em>/**<br>     * Retrieve a user by the given credentials.<br>     *<br>     * </em><strong><em>@param  </em></strong><em>array $credentials<br>     * </em><strong><em>@return </em></strong><em>Authenticatable|null<br>     */<br>    public function </em>retrieveByCredentials(<em>array </em>$credentials)<br>    {<br>        <em>if </em>(<em>empty</em>($credentials) ||<br>            (count($credentials) === 1 &amp;&amp;<br>                array_key_exists(&#39;password&#39;, $credentials))) {<br>            <em>return</em>;<br>        }<br><br>        <em>// find user by email<br>        </em>$userEmail = UserEmail::query()<br>            -&gt;where(&#39;email&#39;, $credentials[&#39;email&#39;])<br>            <em>//</em>-&gt;where(&#39;verified&#39;, 1)<br>            -&gt;first();<br><br>        <em>if </em>(!$userEmail) {<br>            <em>return null</em>;<br>        }<br><br>        <em>return </em>User::find($userEmail-&gt;user_id);<br>    }<br>}</pre><p>Note that -&gt;<em>where(‘verified’, 1)</em> is commented, By default Laravel doesn’t validate if email was verified, you should implement this feature and then you can uncomment to login just users with verified email address.</p><p>Good, after creating our custom authentication provider, we need to say Laravel to use it, for this, let’s change <em>Providers/AuthServiceProvider.php</em></p><pre><em>public function </em>boot()<br>{<br>    $this-&gt;registerPolicies();</pre><pre>    \Auth::provider(&#39;multi.email.auth&#39;, <em>function </em>($app, $config) {<br>        <em>return new </em>MultiEmailAuthentication(<br>            $app[&#39;hash&#39;],<br>            $config[&#39;model&#39;]<br>        );<br>    });<br>}</pre><p>And authentication driver in <em>config/auth.php</em></p><pre>&#39;providers&#39; =&gt; [<br>    &#39;users&#39; =&gt; [<br>        &#39;driver&#39; =&gt; &#39;multi.email.auth&#39;,<br>        &#39;model&#39;  =&gt; App\User::class,<br>    ],<br>],</pre><p>We are almost there, we need to change <em>RegisterController</em> in order to save email address on <em>user_emails</em> instead of <em>users</em></p><pre><em>protected function </em>create(<em>array </em>$data)<br>{<br>    $user = User::create([<br>        &#39;name&#39; =&gt; $data[&#39;name&#39;],<br>        &#39;password&#39; =&gt; bcrypt($data[&#39;password&#39;]),<br>    ]);<br><br>    \App\UserEmail::create([<br>        &#39;email&#39; =&gt; $data[&#39;email&#39;],<br>        &#39;main&#39; =&gt; 1,<br>        &#39;verified&#39; =&gt; 0,<br>        &#39;user_id&#39; =&gt; $user-&gt;id,<br>        &#39;token&#39; =&gt; \Illuminate\Support\Str::random(32),<br>    ]);<br><br>    <em>return </em>$user;<br>}</pre><p>Also in <em>RegisterController </em>remove email from validation array</p><pre><em>protected function </em>validator(<em>array </em>$data)<br>{<br>    <em>return </em>Validator::make($data, [<br>        &#39;name&#39; =&gt; &#39;required|string|max:255&#39;,<br>        &#39;password&#39; =&gt; &#39;required|string|min:6|confirmed&#39;,<br>    ]);<br>}</pre><p>And Finally we can allow <em>App\User</em> model to access email on the same way, this will avoid you to change your code when accessing $user-&gt;email</p><pre><em>/**<br> * </em><strong><em>@var </em></strong><em>string<br> */<br></em>private $userEmailAddress;</pre><pre><em>/**<br> * </em><strong><em>@return </em></strong><em>string<br> */<br>public function </em>getEmailAttribute()<br>{<br>    <em>if </em>(! $this-&gt;userEmailAddress) {<em><br>        </em>$userEmail = UserEmail::query()<br>            -&gt;where(&#39;user_id&#39;, $this-&gt;id)<br>            -&gt;where(&#39;main&#39;, 1)<br>            -&gt;first();<br><br>        $this-&gt;userEmailAddress = $userEmail-&gt;email;<br>    }<br><br>    <em>return </em>$this-&gt;userEmailAddress;<br>}</pre><p>That’s it, now your authentication provider will retrieve the user by it’s id on <em>user_emails</em> table<em>, </em>from here you can do a lot of changes to make it fit well to your application, also you’ll need a page where users can manage email addresses.</p><p>I used Laravel 5.6 to write this post</p><p>Enjoy it :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eee1d8f48e98" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>