<?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 Gabriel Meireles on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Meireles on Medium]]></description>
        <link>https://medium.com/@elmeireles?source=rss-d60aa70b5a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9DLbLyhzHCRagO2RpoDQHg.jpeg</url>
            <title>Stories by Gabriel Meireles on Medium</title>
            <link>https://medium.com/@elmeireles?source=rss-d60aa70b5a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:33:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elmeireles/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[Must-know things before you start with JavaScript: Thread Execution]]></title>
            <link>https://medium.com/dev-meireles/must-know-things-before-you-start-with-javascript-thread-execution-5b87a8e54690?source=rss-d60aa70b5a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b87a8e54690</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Gabriel Meireles]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 15:27:14 GMT</pubDate>
            <atom:updated>2025-01-10T15:27:14.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PBcsicBAIdgSxiC9" /><figcaption>Photo by <a href="https://unsplash.com/@dios4me?utm_source=medium&amp;utm_medium=referral">Bonnie Hawkins</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Thread Execution</h3><p>A thread represents a single sequence of instructions executed within a program. Threads enable multitasking within an application, allowing it to handle multiple operations simultaneously. However, how threads are implemented and behave depends on the programming language and runtime environment.<br>JavaScript can support multithreading in certain environments using constructs like <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers"><strong>Web Workers</strong></a> (in the browser) or <a href="https://nodejs.org/api/worker_threads.html#worker-threads"><strong>Worker Threads</strong></a> (in Node.js). However, JavaScript is inherently <strong>single-threaded</strong> in its main execution model, meaning the main thread can only handle one task at a time.</p><p>In a real world example, if we had to handle 50 different requests from different users using an API built with Node, how would it be?</p><ul><li><strong>Requests are queued:</strong> When 50 requests arrive, Node.js uses the <strong>Event Loop</strong> to process them.</li><li><strong>I/O tasks are offloaded:</strong> CPU-intensive or long-running I/O tasks (like database queries or file reads) are offloaded to:<br>– <strong>Libuv thread pool</strong> (by default, 4 threads for tasks like file system operations).<br>– <strong>Worker Threads</strong> (if explicitly implemented for CPU-bound tasks).</li></ul><h4>So, Simultaneous or Queued?</h4><p><strong>Simultaneous:</strong></p><ul><li>If the I/O operations are non-blocking and the server resources (CPU, memory, threads) can handle the load, <strong>the 50 users will receive their responses asynchronously and seemingly simultaneously</strong>.</li><li>Each I/O operation is managed independently, so no single request blocks others.</li></ul><p><strong>Queued (First-Come, First-Served Basis):</strong></p><ul><li>If a request involves blocking code or if the server resources are exhausted, subsequent requests may appear to be queued.</li><li>Example: If the server is overwhelmed by CPU-bound tasks, the Event Loop gets blocked, and responses are delayed until earlier tasks complete.</li></ul><h4>What Happens with 50 Requests?</h4><ul><li><strong>Request Queuing: </strong>Each incoming request is placed in the Event Loop’s queue.</li><li><strong>Event Loop Execution: </strong>The Event Loop picks up requests one at a time, processes them, and offloads blocking I/O to worker threads.</li><li><strong>Response: </strong>Once the task (e.g., database query) completes, the callback is queued to return the response.</li></ul><h3>Performance and Threads</h3><h4><strong>Good Case (I/O-Bound Workloads):</strong></h4><ul><li>Tasks like database queries, API calls, or file reads are perfect for JavaScript’s event-driven model. These are non-blocking and do not require multithreading.</li></ul><h4>Bad Case (CPU-Bound Workloads):</h4><ul><li>Long-running, CPU-intensive tasks (e.g., image processing, large calculations) block the main thread, degrading performance.</li><li>If one request triggers this task, all other requests will stall, as the Event Loop is blocked:</li></ul><pre>app.get(&#39;/heavy-task&#39;, (req, res) =&gt; {<br>  const result = Array(1e8).fill().reduce((acc, _, i) =&gt; acc + i, 0); // Blocks the Event Loop<br>  res.send(`Result: ${result}`);<br>});</pre><p>Thread execution is a fundamental concept that dictates how a program handles and processes tasks. In JavaScript, the single-threaded nature of the runtime, combined with its non-blocking, event-driven model, enables efficient handling of I/O-bound workloads. While the main thread handles execution, asynchronous operations are delegated to background threads or external systems, ensuring responsiveness and scalability.</p><p>However, this model can face challenges with CPU-bound tasks, as they block the Event Loop and delay subsequent operations. To mitigate this, multithreading solutions like <strong>Worker Threads</strong> in Node.js or <strong>Web Workers</strong> in the browser can offload heavy computations, improving performance.</p><p>Understanding when to use the single-threaded model versus multithreading is key to building high-performing and scalable applications. By leveraging the strengths of asynchronous programming and multithreading when appropriate, developers can achieve a balance between simplicity and performance in modern applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b87a8e54690" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-meireles/must-know-things-before-you-start-with-javascript-thread-execution-5b87a8e54690">Must-know things before you start with JavaScript: Thread Execution</a> was originally published in <a href="https://medium.com/dev-meireles">dev.meireles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Powerful Applications with Laravel — Basic CRUD Operations]]></title>
            <link>https://medium.com/dev-meireles/powerful-applications-with-laravel-basic-crud-operations-a5f843b641c2?source=rss-d60aa70b5a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5f843b641c2</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gabriel Meireles]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 16:21:28 GMT</pubDate>
            <atom:updated>2023-03-15T16:21:28.860Z</atom:updated>
            <content:encoded><![CDATA[<h3>Powerful Applications with Laravel — Basic CRUD Operations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UC6_0_ocmsErSvGj" /><figcaption>Photo by <a href="https://unsplash.com/@robinpierre?utm_source=medium&amp;utm_medium=referral">Robin Pierre</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In a nutshell <strong>CRUD </strong>is an acronym widely famous in the world of computer programming that’s used to refer to basic operations known as <strong>Create</strong>, <strong>Read</strong>, <strong>Update </strong>and <strong>Delete</strong>. Throughout your life as a developer it’ll be really common to deal with models performing these functions.</p><p>Often, almost 100% as a rule controllers will interact with models, for example, in a e-commerce system where an user must be able to see a list of products we know there’s an entrypoint / route for products that’ll call the ProductController, in its turn will interact with the ProductModel that under the hood will execute a query on your system database, something usually like SELECT * FROM products, it could be the <strong>R</strong> as <strong>Read</strong>.</p><p>First of all, make sure to import the Product model use App\Models\Product</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Models\Product;<br>use Illuminate\Http\Request;<br><br>class ProductController extends Controller<br>{</pre><h4>C as Create</h4><p>So let’s start implementing a functionality that’ll enable a user to create a new product on database:</p><pre>/**<br> * Store a newly created resource in storage.<br>*/<br>public function store(Request $request)<br>{<br>    $product = new Product();<br>    $product-&gt;name = $request-&gt;input(&#39;name&#39;);<br>    $product-&gt;description = $request-&gt;input(&#39;description&#39;);<br>    $product-&gt;price = $request-&gt;input(&#39;price&#39;);<br>    $product-&gt;save();<br><br>    return response()-&gt;json([<br>        &#39;success&#39;   =&gt;  true,<br>        &#39;data&#39;      =&gt;  $product,<br>    ]);<br>}</pre><h4>R as Read</h4><p>Once we already have an inserted product on the database it’s time to retrieve / read it, for a list of items</p><pre>/**<br>* Display a listing of the resource.<br>*/<br>public function index()<br>{<br>  $products = Product::all();<br>  return response()-&gt;json([<br>      &quot;success&quot;   =&gt;  true,<br>      &quot;data&quot;      =&gt;  $products,<br>  ]);<br>}</pre><p>And for an individual item by id:</p><pre>/**<br>* Display the specified resource.<br>*/<br>public function show(int $id)<br>{<br>  $product = Product::find($id);<br><br>  return response()-&gt;json([<br>      &#39;success&#39;   =&gt;  true,<br>      &#39;data&#39;      =&gt;  $product,<br>  ]);<br>}</pre><h4>U as Update</h4><p>Now the update function that’ll update a current existent item:</p><pre>/**<br>* Update the specified resource in storage.<br>*/<br>public function update(Request $request, int $id)<br>{<br>  $product = Product::find($id);<br>  $product-&gt;name = $request-&gt;input(&#39;name&#39;);<br>  $product-&gt;description = $request-&gt;input(&#39;description&#39;);<br>  $product-&gt;price = $request-&gt;input(&#39;price&#39;);<br>  $product-&gt;save();<br><br>  return response()-&gt;json([<br>      &#39;success&#39;   =&gt;  true,<br>      &#39;data&#39;      =&gt;  $product,<br>  ]);<br>}</pre><h4>D as Delete</h4><p>And finally the delete that must remove an item based on id:</p><pre>/**<br>* Remove the specified resource from storage.<br>*/<br>public function destroy(int $id)<br>{<br>  Product::destroy($id);<br>}</pre><p>As a rule of thumb these are the basic and primordial operations which will be your whole life partner as a developer, for sure, according to as your application increases and gets more complex, these functionalities probably will increase and turn on more complex so.</p><p>As you know, you can find the current updates on <a href="https://github.com/devmeireles/laravel-powerful-apps/tree/03-controller-model">Github repository</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5f843b641c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-meireles/powerful-applications-with-laravel-basic-crud-operations-a5f843b641c2">Powerful Applications with Laravel — Basic CRUD Operations</a> was originally published in <a href="https://medium.com/dev-meireles">dev.meireles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Powerful Applications with Laravel — Database and Migrations]]></title>
            <link>https://medium.com/dev-meireles/powerful-applications-with-laravel-database-and-migrations-bc8748328308?source=rss-d60aa70b5a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc8748328308</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gabriel Meireles]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 12:22:00 GMT</pubDate>
            <atom:updated>2023-03-11T12:22:00.084Z</atom:updated>
            <content:encoded><![CDATA[<h3>Powerful Applications with Laravel — Database and Migrations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*al4AoWJOEgCGYrR1" /><figcaption>Photo by <a href="https://unsplash.com/@ubahnverleih?utm_source=medium&amp;utm_medium=referral">C M</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>After knowing that controllers are responsible for route commands for our application, that’s time to explain a bit about <strong>model </strong>which is also a pretty important layer of <strong>MCV. </strong>Briefly models are responsible for handle data and business logic on an application. With a model we have control about what kind of data the app have control, send and receive data operations to a controller.</p><blockquote>Model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller). — <a href="http://www.dgp.toronto.edu/~dwigdor/teaching/csc2524/2012_F/papers/mvc.pdf">Applications Programming in Smalltalk-80 (TM): How to use Model-View-Controller (MVC) — Steve Burbeck</a></blockquote><p>I dare to say that nowadays almost all applications in somehow depends on a database connection whether it a real <strong>DBMS, </strong>a cache system or even a text file. There’s a widely quantity of applications which uses database, as examples applications that we’re are used to interact in our daily life that stores credential access, emails, images, movies, allow us to watch a video, read an article, ask for a cab or whatever is it, they need to have some way to store data.</p><h4>Connecting to database</h4><p>Take into account Laravel is fully flexible in terms of database providing support for five databases, MariaDB, MySQL, PostgreSQL, SQLite and SQL Server, besides, there are other possibilities as DynamoDB with <a href="https://github.com/kitar/laravel-dynamodb">Laravel DynamoDB</a>, MongoDB with <a href="https://github.com/jenssegers/laravel-mongodb">Laravel MongoDB</a>, Oracle with <a href="https://github.com/yajra/laravel-oci8">Laravel-OCI8</a> and so on.</p><p>For this series we`re going to use PostgreSQL database, so if you’re using the initial Docker repository <a href="https://medium.com/dev-meireles/powerful-applications-with-laravel-setting-up-docker-17f64d8e10f1">featured in the first part of this series</a> you can easily get the environment variables for database on <a href="https://github.com/devmeireles/laravel-powerful-apps/blob/main/docker-compose.yml">docker-compose.yml</a> file under the postgres section, but feel free to user a database connection of your choice. So if you don`t have a .env file yet, please copy the .env.example and update according to the following section:</p><pre>DB_CONNECTION=pgsql<br>DB_HOST=127.0.0.1<br>DB_PORT=5432<br>DB_DATABASE=laraveldb<br>DB_USERNAME=postgres<br>DB_PASSWORD=password</pre><h4>Migrations</h4><p>Migrations look like a git version control allowing the developer to properly handle database schemas from their current state to a new desired state that includes actions like adding tables, columns, relationships and also remove them.<br>As properly stated in Laravel documentation: “migrations are like version control for your database, allowing your team to define and share the application’s database schema definition. If you have ever had to tell a teammate to manually add a column to their local database schema after pulling in your changes from source control, you’ve faced the problem that database migrations solve.</p><p>With Artisan we’ve different alternatives to generate migrations, so you can generate a simple migration file using:<br>(Make sure to access your docker container, all following commands will be executed inside there)</p><pre>php artisan make:migration create_products_table</pre><p>On app/database/migrations folder it’ll creates a PHP file containing the generated migration script:</p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     */<br>    public function up(): void<br>    {<br>        Schema::create(&#39;products&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    /**<br>     * Reverse the migrations.<br>     */<br>    public function down(): void<br>    {<br>        Schema::dropIfExists(&#39;products&#39;);<br>    }<br>};</pre><p>A quickly explanation:</p><ul><li>With <em>Schema::create</em> Laravel generates the table, the first parameter is the table name and the second a callback containing the table properties.</li><li>Using the <em>Blueprint </em>class through the <em>$table</em> variable you can set your table properties, it’s basically setting the table id using the <em>bigIncrements </em>type that’ll setup the necessary properties for an id type</li></ul><p>I recommend you to take a look on <a href="https://laravel.com/docs/9.x/migrations#available-column-types"><strong>Available Column Types</strong></a> on Laravel documentation, after that try to add some columns and finally execute your migration with:</p><pre>php artisan migrate</pre><p>After that if everything went as expected it must generate you products table, so you can see them using some database GUI tool of your choice or use the pgAdmin that’s included on our docker setup accessing <a href="http://localhost:5050/">http://localhost:5050/</a> with admin@example.com as user and password as password.</p><p>Now it’s time to rollback the product table, we’ll do some changes:</p><pre>php artisan migrate:rollback</pre><p>As said before, there’re some another ways to generate migrations, so let’s try them.</p><p>With the <em>make:model </em>we can use some parameters like <strong><em>-c</em></strong> to say we want to have a controller for this created model, <strong><em>-m</em></strong> for migration and <strong><em>-r </em></strong>for the created controller resources, what means, it’ll create the CRUD scaffolding for this current entity. I recommend you to take a look on Generating Model Classes section on Laravel documentation:</p><p><a href="https://laravel.com/docs/10.x/eloquent#generating-model-classes">Laravel - The PHP Framework For Web Artisans</a></p><p>For this step make sure to remove the previous create_products_table migration file, then let’s create a product model, to se how it goes:</p><pre>php artisan make:model Product --migration</pre><p>With that now we’ve a file for Product as model and a create_products_table as migration.</p><p>On products migration file, let`s add some columns as:</p><pre>&lt;?php<br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     */<br>    public function up(): void<br>    {<br>        Schema::create(&#39;products&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;longText(&#39;description&#39;);<br>            $table-&gt;double(&#39;price&#39;);<br>            $table-&gt;boolean(&#39;active&#39;)-&gt;default(true);<br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    /**<br>     * Reverse the migrations.<br>     */<br>    public function down(): void<br>    {<br>        Schema::dropIfExists(&#39;products&#39;);<br>    }<br>};</pre><p>Then finally it’s time do definitively migrate, so on you terminal do the following command:</p><pre>php artisan migrate</pre><p>On pgAdmin you can see you recently created table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jV3lhVGO_ed6F0llnVmT7Q.png" /></figure><p>So far that’s all folks, see you next step to start the Controller + Model interactions. All current updates are place on <a href="https://github.com/devmeireles/laravel-powerful-apps/tree/02-model-database"><strong>GitHub repository</strong></a>, feel free to explore them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc8748328308" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-meireles/powerful-applications-with-laravel-database-and-migrations-bc8748328308">Powerful Applications with Laravel — Database and Migrations</a> was originally published in <a href="https://medium.com/dev-meireles">dev.meireles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Powerful Applications with Laravel — Routes and Controllers]]></title>
            <link>https://medium.com/dev-meireles/powerful-applications-with-laravel-routes-and-controllers-2110dd82d51c?source=rss-d60aa70b5a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2110dd82d51c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Gabriel Meireles]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 20:30:07 GMT</pubDate>
            <atom:updated>2023-03-15T16:14:35.065Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/dev-meireles/powerful-applications-with-laravel-setting-up-docker-17f64d8e10f1?source=your_stories_page-------------------------------------">Powerful Applications with Laravel</a> — Routes and Controllers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OR3qINOBAnVX_jMS" /><figcaption>Photo by <a href="https://unsplash.com/@16bitspixelz?utm_source=medium&amp;utm_medium=referral">Kamil S</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>MVC is a shortening for Model, View, and <strong>Controller </strong>that appears 70s late on <a href="http://www.dgp.toronto.edu/~dwigdor/teaching/csc2524/2012_F/papers/mvc.pdf">Smalltalk-80 by Xerox PARC</a> emphasizing that a <strong>controller </strong>is an intermediary layer responsible for receive commands from an user interacting with the application.</p><blockquote>When building interactive applications, as with other programs, modularity of components has enormous benefits. Isolating functional units from each other as much as possible makes it easier for the application designer to understand and modify each particular unit without having to know everything about the other units. — <a href="https://www.ics.uci.edu/~redmiles/ics227-SQ04/papers/KrasnerPope88.pdf">A Cookbook for Using View-Controller User the Model Interface Paradigm in Smalltalk-80 — Glenn E. Krasner and Stephen T. Pope</a></blockquote><p>Majority the frameworks entry points are on <strong>routes </strong>and for <strong>Laravel </strong>it isn’t different, as example, when working for web you probably have seen addresses like <strong><em>example.com/product/1 </em></strong>or <strong><em>example.com/product/nice-new-laptop </em></strong>and for web application it usually means there are a route that’ll receive a request whether GET, POST, no matter the verb, then deal as it must be dealt and the responsible for handle these requests are the <strong>controllers</strong>, instead of execute all business logic directly in a <strong>route </strong>we can transfer this responsibility to a <strong>controller </strong>and is it how <strong>Laravel </strong>works.</p><h4>Generating Controllers</h4><p>You can easily generate <strong>controllers </strong>using Artisan, so let’s create an initial one:</p><pre>docker exec -it laravel-powerful-apps-php-1 php artisan make:controller ProductController</pre><p>Which will generate a <strong><em>ProductController.php</em></strong> file on <strong><em>src/app/Http/Controllers</em></strong>:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br><br>class ProductController extends Controller<br>{<br>    //<br>}</pre><p>Quite simple, doesn’t? You can also generate <strong>controllers </strong>with CRUD functionalities already placed using --resource (remember to remove the current <strong><em>ProductController.php</em></strong> before executing the following command)</p><pre>docker exec -it laravel-powerful-apps-php-1 php artisan make:controller ProductController --resource</pre><p>It’ll generate the following structure:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br><br>class ProductController extends Controller<br>{<br>    /**<br>     * Display a listing of the resource.<br>     */<br>    public function index()<br>    {<br>        //<br>    }<br><br>    /**<br>     * Show the form for creating a new resource.<br>     */<br>    public function create()<br>    {<br>        //<br>    }<br><br>    /**<br>     * Store a newly created resource in storage.<br>     */<br>    public function store(Request $request)<br>    {<br>        //<br>    }<br><br>    /**<br>     * Display the specified resource.<br>     */<br>    public function show(string $id)<br>    {<br>        //<br>    }<br><br>    /**<br>     * Show the form for editing the specified resource.<br>     */<br>    public function edit(string $id)<br>    {<br>        //<br>    }<br><br>    /**<br>     * Update the specified resource in storage.<br>     */<br>    public function update(Request $request, string $id)<br>    {<br>        //<br>    }<br><br>    /**<br>     * Remove the specified resource from storage.<br>     */<br>    public function destroy(string $id)<br>    {<br>        //<br>    }<br>}</pre><p>Once you already have an initial <strong>controller</strong>, let’s create a <strong>route </strong>to operate them, so your <strong><em>src/routes/web.php </em></strong>must looks like:</p><pre>&lt;?php<br><br>use App\Http\Controllers\ProductController;<br>use Illuminate\Support\Facades\Route;<br><br><br>Route::name(&#39;product.&#39;)-&gt;group(function () {<br>    Route::get(&#39;/products&#39;, [ProductController::class, &#39;index&#39;])-&gt;name(&#39;list&#39;);<br>    Route::get(&#39;/products/{id}&#39;, [ProductController::class, &#39;show&#39;])-&gt;name(&#39;show&#39;);<br>    Route::post(&#39;/products&#39;, [ProductController::class, &#39;store&#39;])-&gt;name(&#39;save&#39;);<br>    Route::put(&#39;/products/{id}&#39;, [ProductController::class, &#39;update&#39;])-&gt;name(&#39;update&#39;);<br>    Route::delete(&#39;/products/{id}&#39;, [ProductController::class, &#39;destroy&#39;])-&gt;name(&#39;remove&#39;);<br>});</pre><p>There are a lot of possibilities when dealing with routes, one of them is using the resource option that’ll compile all possible verbs together:</p><pre>&lt;?php<br><br>use Illuminate\Support\Facades\Route;<br>use App\Http\Controllers\ProductController;<br><br>/*<br>|--------------------------------------------------------------------------<br>| Web Routes<br>|--------------------------------------------------------------------------<br>|<br>| Here is where you can register web routes for your application. These<br>| routes are loaded by the RouteServiceProvider and all of them will<br>| be assigned to the &quot;web&quot; middleware group. Make something great!<br>|<br>*/<br><br>Route::get(&#39;/&#39;, function () {<br>    return view(&#39;welcome&#39;);<br>});<br> <br>Route::resource(&#39;products&#39;, ProductController::class);</pre><p>Let’s keep the first routing option, it’ll be util thereafter.</p><p>Then backing to <strong><em>ProductController.php </em></strong>let’s add some lines of code to see the products <strong>route </strong>working, it must return a JSON response containing a list of products:</p><pre>class ProductController extends Controller<br>{<br><br>    private $products = [];<br><br>    function __construct()<br>    {<br>        $this-&gt;products = [<br>            (object)[<br>                &#39;id&#39;    =&gt;  1,<br>                &#39;name&#39;  =&gt;  &#39;New Shoes&#39;<br>            ],<br>            (object)[<br>                &#39;id&#39;    =&gt;  2,<br>                &#39;name&#39;  =&gt;  &#39;Cool T-shirt&#39;<br>            ],<br>        ];<br>    }<br><br>    /**<br>     * Display a listing of the resource.<br>     */<br>    public function index()<br>    {<br>        return response()-&gt;json($this-&gt;products);<br>    }</pre><p>Accessing <a href="http://localhost/products">http://localhost/products</a> you’ll see the JSON response:</p><pre>{<br>    &quot;success&quot;: true,<br>    &quot;data&quot;: [<br>        {<br>            &quot;id&quot;: 1,<br>            &quot;name&quot;: &quot;New Shoes&quot;<br>        },<br>        {<br>            &quot;id&quot;: 2,<br>            &quot;name&quot;: &quot;Cool T-shirt&quot;<br>        }<br>    ]<br>}</pre><p>Following the same example, now we can get an item by id, so let’s implement it on ProductController:</p><pre>public function show(int $id)<br>{<br>    $search = array_filter($this-&gt;products, fn ($item) =&gt; $item-&gt;id === $id);<br>    $product = reset($search);<br><br>    return response()-&gt;json([<br>        &#39;success&#39;   =&gt;  true,<br>        &#39;data&#39;      =&gt;  $product,<br>    ]);<br>}</pre><p>Accessing to <a href="http://localhost/products/1">http://localhost/products/1</a> the result must be:</p><pre>{<br>    &quot;success&quot;: true,<br>    &quot;data&quot;: {<br>        &quot;id&quot;: 1,<br>        &quot;name&quot;: &quot;New Shoes&quot;<br>    }<br>}</pre><p>To do read, update and delete operations you must have some permissions controlled by <a href="https://laravel.com/docs/10.x/csrf">CSRF token</a>, so for now just to test these features let’s do some changes aiming to forgive temporally the token process, so on <strong><em>src\app\Http\Middleware\VerifyCsrfToken.php </em></strong>add the following change:</p><pre>&lt;?php<br><br>namespace App\Http\Middleware;<br><br>use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;<br><br>class VerifyCsrfToken extends Middleware<br>{<br>    /**<br>     * The URIs that should be excluded from CSRF verification.<br>     *<br>     * @var array&lt;int, string&gt;<br>     */<br>    protected $except = [<br>        &#39;*&#39;<br>    ];<br>}</pre><p>Then backing to <strong>controller </strong>implement the create function:</p><pre>public function store(Request $request)<br>{<br>    $product = new stdClass();<br>    $product-&gt;name = $request-&gt;input(&#39;name&#39;);<br>    $product-&gt;id = date_timestamp_get(date_create());<br><br>    array_push($this-&gt;products, $product);<br><br>    print_r($this-&gt;products);<br><br>    return response()-&gt;json([<br>        &#39;success&#39;   =&gt;  true,<br>        &#39;data&#39;      =&gt;  $product,<br>    ]);<br>}</pre><p>With that a new product value will be place on $this-&gt;products variable, you can use some automated testing software such as Postman, Inmsomina or even <a href="https://marketplace.visualstudio.com/items?itemName=rangav.vscode-thunder-client">Thunder Client</a> if you’re using VS Code.</p><p>A pretty similar process must be done to update a product value according to the id, so on update function let’s implement:</p><pre>public function update(Request $request, int $id)<br>{<br>    $search = array_filter($this-&gt;products, fn ($item) =&gt; $item-&gt;id === $id);<br>    $product = reset($search);<br><br>    $product-&gt;name = $request-&gt;input(&#39;name&#39;);<br><br>    return response()-&gt;json([<br>        &#39;success&#39;   =&gt;  true,<br>        &#39;data&#39;      =&gt;  $product,<br>    ]);<br>}</pre><p>And finally for remove an item by id let’s implement the destroy function:</p><pre>public function destroy(int $id)<br>{<br>    $search = array_filter($this-&gt;products, fn ($item) =&gt; $item-&gt;id === $id);<br>    $key = array_key_first($search);<br>    unset($this-&gt;products[$key]);<br><br>    var_dump($this-&gt;products);<br>}</pre><p>I really recommend you to take a look on Routes section under Laravel documentation</p><p><a href="https://laravel.com/docs/10.x/routing">Laravel - The PHP Framework For Web Artisans</a></p><p>And here other important resources:</p><ul><li><a href="https://laravel.com/docs/10.x/csrf">Laravel - The PHP Framework For Web Artisans</a></li><li><a href="https://laravel.com/docs/10.x/controllers#main-content">Laravel - The PHP Framework For Web Artisans</a></li></ul><p>All these changes are placed on <a href="https://github.com/devmeireles/laravel-powerful-apps/tree/01-controllers-routes"><strong>GitHub</strong></a>, feel free to explore.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2110dd82d51c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-meireles/powerful-applications-with-laravel-routes-and-controllers-2110dd82d51c">Powerful Applications with Laravel — Routes and Controllers</a> was originally published in <a href="https://medium.com/dev-meireles">dev.meireles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Powerful Applications with Laravel — Setting up Docker]]></title>
            <link>https://medium.com/dev-meireles/powerful-applications-with-laravel-setting-up-docker-17f64d8e10f1?source=rss-d60aa70b5a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/17f64d8e10f1</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Gabriel Meireles]]></dc:creator>
            <pubDate>Thu, 09 Mar 2023 14:26:09 GMT</pubDate>
            <atom:updated>2023-03-09T14:26:09.427Z</atom:updated>
            <content:encoded><![CDATA[<h3>Powerful Applications with Laravel — Setting up Docker</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lAJ9fw8sQj3KeKIB" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@ishant_mishra54?utm_source=medium&amp;utm_medium=referral">Ishant Mishra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello there! I’m really delighted to start talking about <strong>Laravel </strong>through a series of articles where we’ll cover some important points about this amazing <strong>PHP Framework.<br></strong>First of all, make sure to really know at least the basics of MVC and OOP using PHP, I recommend recapping an overview on these initial subjects.</p><p>Throughout this series of articles we’ll learn how to build a robust <strong>Laravel </strong>application from zero. Let’s cover initial setups as basic MVC, authentication, databases, validations, email services, code refactor, patterns, tests, and a bit more.</p><h4>A quickly Introduction</h4><p>Built by <a href="https://github.com/taylorotwell">Taylor Otwell</a> in June 2011 and currently on version 10, <a href="https://laravel.com/docs/master"><strong>Laravel </strong></a>is a web application framework that aims to provide a great, simple and readable skeleton for your application with features such as <a href="https://laravel.com/docs/master/eloquent"><strong>Eloquent ORM</strong></a> that offers an interactive object-relational mapper or even the <a href="https://laravel.com/docs/master/artisan"><strong>Artisan </strong></a>which provides a number of helpful commands that can assist you while building your application through a command line interface; We also have some important features like <a href="https://laravel.com/docs/master/blade"><strong>Blade</strong> </a>as template engine, the <a href="https://laravel.com/docs/master/migrations"><strong>Schema facade</strong></a> to deal with your database migrations and <a href="https://vitejs.dev/guide/"><strong>Vite</strong></a><strong> </strong>to build progressive user interfaces.</p><h4>Starting with Docker</h4><p>Shall we start by creating the necessary structure to have an initial executable Laravel setup, back in the days we were used to have local environments provides by EasyPHP, the classical XAMPP (depends on your OS it could be LAMPP or MAMPP) or even WampServer, anyway, let’s use <strong>Docker </strong>to create some containers to keep our development process fast, consistent and strong allowing us to take advantage of a powerful standardized local environments, so without any furthermore, let’s start!</p><p>Make sure to have the Docker setup:</p><pre>docker --version</pre><p>If you don’t have it, please follow the Docker installation guide:</p><p><a href="https://docs.docker.com/get-docker/">Get Docker</a></p><p>You can get a <strong>Laravel + Docker</strong> setup over here:</p><p><a href="https://github.com/devmeireles/laravel-powerful-apps">GitHub - devmeireles/laravel-powerful-apps</a></p><p>In this repository you can found a docker-compose.yml file which is responsible for build the <strong>PHP </strong>+ <strong>Ngnix </strong>containers</p><pre>version: &#39;3&#39;<br><br>networks:<br>  laravel:<br><br>services:<br>  app:<br>    build:<br>      context: ./docker<br>      dockerfile: nginx.dockerfile<br>      args:<br>        - UID=${UID:-1000}<br>        - GID=${GID:-1000}<br>    ports:<br>      - &quot;80:80&quot;<br>    volumes:<br>      - ./src:/var/www/html:delegated<br>    depends_on:<br>      - php<br>    networks:<br>      - laravel<br><br>  php:<br>    build:<br>      context: ./docker<br>      dockerfile: php.dockerfile<br>      args:<br>        - UID=${UID:-1000}<br>        - GID=${GID:-1000}<br>    ports:<br>      - &quot;9000:9000&quot;<br>    volumes:<br>      - ./src:/var/www/html:delegated<br>    networks:<br>      - laravel</pre><p>After cloning the repository you must have the following file structure:</p><pre>├── .<br>├── docker/<br>│  └── nginx<br>│    └── default.conf<br>│  ├── nginx.dockerfile <br>│  └── php.dockerfile <br>├── src/ <br>│  └── LARAVEL FOLDER<br>└── docker-compose.yml</pre><p>Briefly, <strong>docker </strong>folder contains dockerfiles responsible for building the container images installing dependencies and apk necessaries to maintain the runtime, lastly, <strong>src </strong>contains the <strong>Laravel </strong>installation where we’ll work building our application.</p><h4>Wrapping all together</h4><p>Now you have and know how the setup works, let’s start executing some commands necessaries to run the application, first of all, build and up the containers on mainly folder (where you cloned the repository from git) executing the following command:</p><pre>docker-compose up --build</pre><p>It’ll probably take a while to install all dependencies, when done, copy the .env file:</p><pre>cp src/.env.example src/.env</pre><p>Then get the current PHP container with <a href="https://docs.docker.com/engine/reference/commandline/ps/"><strong>docker ps command</strong></a><strong> </strong>to list your current containers:</p><pre>docker ps</pre><p>In my case the container with PHP is <strong><em>laravel-powerful-apps-php-1, </em></strong>so it’s time to install the Laravel dependencies with Composer:</p><pre>docker exec -it laravel-powerful-apps-php-1 composer install</pre><p>And finally generate a key:</p><pre>php artisan key:generate</pre><p>After that you must be able to access the application on your browser <a href="http://localhost/">http://localhost</a> and see the your brand new <strong>Laravel </strong>setup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17f64d8e10f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-meireles/powerful-applications-with-laravel-setting-up-docker-17f64d8e10f1">Powerful Applications with Laravel — Setting up Docker</a> was originally published in <a href="https://medium.com/dev-meireles">dev.meireles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-Oriented Programming with TypeScript — Encapsulation]]></title>
            <link>https://medium.com/dev-meireles/object-oriented-programming-with-typescript-encapsulation-1f1835a99339?source=rss-d60aa70b5a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f1835a99339</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Gabriel Meireles]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 14:34:01 GMT</pubDate>
            <atom:updated>2022-06-13T14:34:01.147Z</atom:updated>
            <content:encoded><![CDATA[<h3>Object-Oriented Programming with TypeScript — Encapsulation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WJv6QzNBTrDnvHe1" /><figcaption>Photo by <a href="https://unsplash.com/@mihaiteslariu0?utm_source=medium&amp;utm_medium=referral">Teslariu Mihai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hey everyone! Still talking about Object-Oriented Programming, today I would like to introduce a bit about encapsulation, with this OOP key-concept we’ll grasp some crucial concepts when building a class.<br>Hope you’d read the last article when I’m talking about Abstraction, if not, it’s time:</p><p><a href="https://medium.com/dev-meireles/object-oriented-programming-with-typescript-abstraction-4dcd976c8ae2">Object-Oriented Programming with TypeScript — Abstraction</a></p><h3>What is Encapsulation?</h3><p>Encapsulation is the capability of binding data as class attributes and methods as behavioural function, in other words, encapsulation is the act of build and manipulate data through methods into a single unit.<br>Oh well! Here we’ll go again! It seems a bit hard to understand, but it’s easier than you think.</p><p>Here’s a pretty good definition from <a href="https://www.w3schools.com/">W3Schools</a>:</p><p>The meaning of <strong>Encapsulation</strong>, is to make sure that “sensitive” data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide public get and set methods.</p><p>So taking this point of view into account we can figure out and exemplify some code, I think we can still using our soda fountain machine presented at last time on <a href="https://medium.com/dev-meireles/object-oriented-programming-with-typescript-abstraction-4dcd976c8ae2"><strong>Object-Oriented Programming with TypeScript — Abstraction</strong></a>.</p><p>We’ll release a new feature turning our machine able to sell beer, ask the client name and age and if the client is under 18 and trying to buy a beer the transaction must be reject, otherwise should proceed with the purchase.</p><h3>Let’s code!</h3><p>Considering the presented features, let’s start adding new properties aka class attributes, in this case clientName as string clientAge as number and isAlcoholic as boolean.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c86ec67db6fa6cf4d09fbfb64fa27edd/href">https://medium.com/media/c86ec67db6fa6cf4d09fbfb64fa27edd/href</a></iframe><p><strong>L#15, L#16 and L#17 — </strong>Declaring the class attributes<br><strong>L#25 — </strong>Setting the class constructor, that works as a method executed always when you instantiate your class<br><strong>L#48, L#49 — </strong>Instantiating the sodaMachine class, this time with initial attributes as clientName clientAge and isAlcoholic <br><strong>L#54 — </strong>Printing the clientName</p><p>Keeping the clientName value as public allows this sensitive data being accessed and in view of “make sure that sensitive data is hidden from users” it’s not a good idea keep it public, so let’s change the <strong>L#15 </strong>from public clientName: string to private clientName: string</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*IAhSiq_jhiqbulHI.jpg" /></figure><h3>Getters and Setters are your friends</h3><p>This due is extremally important when encapsulating a class, through them you can write and read values for your class attributes, so a <strong>getter </strong>is a <strong>reader-only</strong> and a <strong>setter </strong>is a <strong>writer-only</strong>, and both are public methods that’ll provide access to your class attributes, so let’s implement them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ddfe384f43bd54c68b5f9220cc82e36/href">https://medium.com/media/2ddfe384f43bd54c68b5f9220cc82e36/href</a></iframe><p><strong>L#15 — </strong>Moving the class attributes clientName from public to private limiting the external access<br><strong>L#35 and L#43 — </strong>Setters for clientName and clientAge <br><strong>L#51 and L#59 — </strong>Getters for clientName and clientAge <br><strong>L#87 and L#90 — </strong>Printing the client names using the get method</p><p><strong>Keep in mind: </strong>Usually getters methods starts as “get” and setters as set followed by a variable name, in both, the first letter of the variable’s name should be capitalized a getter and setter for a variable called country will be getCountry and setCountry</p><p>With setters we can easily change our object properties values, in this case I want to change the client name, I’d started with John but it should be Mark, so what should I do to fix it? Maybe create a new purchase like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a50ed51daa9f635c87280f9c8c089cf/href">https://medium.com/media/9a50ed51daa9f635c87280f9c8c089cf/href</a></iframe><p>Or better, we just can make us of our setters methods, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5418aa6d1c38811506b77ebad7a6db96/href">https://medium.com/media/5418aa6d1c38811506b77ebad7a6db96/href</a></iframe><p>So now we know exactly how to use getters and setters we can finally implement our new features:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd9c49e9e45f7bf930df3b58e30668af/href">https://medium.com/media/bd9c49e9e45f7bf930df3b58e30668af/href</a></iframe><p>Great! We did it! Taking into account “sensitive data is hidden from users” we add new features for the SodaMachine making good use of Encapsulation, see you next time to talk about Inheritance, looking forward!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f1835a99339" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-meireles/object-oriented-programming-with-typescript-encapsulation-1f1835a99339">Object-Oriented Programming with TypeScript — Encapsulation</a> was originally published in <a href="https://medium.com/dev-meireles">dev.meireles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns — Singleton]]></title>
            <link>https://medium.com/dev-meireles/design-patterns-singleton-5071cfb88c33?source=rss-d60aa70b5a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5071cfb88c33</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Gabriel Meireles]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 15:39:34 GMT</pubDate>
            <atom:updated>2022-04-06T15:39:34.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrASdqLdw8ssLkzYzqDd6A.jpeg" /><figcaption><a href="https://unsplash.com/photos/DoSDQvzjeH0">Photo</a> by <a href="https://unsplash.com/@jruscello">Jessica Ruscello</a></figcaption></figure><h3>Design Patterns — Singleton</h3><p>Hello there! In this article let’s talk a bit about <strong>Design Patterns</strong>, specifically regarding to <strong>Singleton</strong>. Let’s start our journey through the learning path with the <strong>Creational Design Patterns</strong>.</p><h4>What is Singleton?</h4><p>The <strong>Singleton </strong>is one of the <strong>Creational Design Pattern</strong> that’s part of the <strong>Gang of Four</strong> also know as <strong>GoF</strong>. This pattern ensures that a class has only an unique instance providing a global entry point, so it means, your class can only be instantiated once, exemplifying:</p><h4>When use Singleton?</h4><p>Taking into account that a Singleton class has an unique instance, you can consider to use it on your application that should have just a single instance of your class available, as example, a class that contains a method to connect and disconnect your code application to a database so with that you don’t need to request a new connection for every query or request; You can consider a log class that’ll persists throughout your application or even a class to initiate and persists some settings for your code, exemplifying:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/412304560b3aad3c4a406743c75bf3ae/href">https://medium.com/media/412304560b3aad3c4a406743c75bf3ae/href</a></iframe><p>The class Register has two properties, _instance and count and two methods getInstance and setCount</p><p><strong>Line#8 </strong>— The_instance property that should be accessed only by Register class<br><strong>Line#13 </strong>— The count property<br><strong>Line#19 </strong>—<strong> </strong>Setting the getInstance method, it’ll accessed when we need to instantiate the Register class<br><strong>Line#27 </strong>—<strong> </strong>setCount method that will receive a number and update the this.count value<br>The <strong>Singleton</strong> magic happens on line 20 on getInstance method, it’ll try to return the this._instance if it exists, otherwise it’ll create a new instance using the this() and set it as value of this._instance <br>Pure rocket science, isn’t?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/602432f6ce25d39a34e4f283f5613b2b/href">https://medium.com/media/602432f6ce25d39a34e4f283f5613b2b/href</a></iframe><p>Let’s execute the Register class to see their behavior and the step by step:</p><p><strong>Line#4</strong> and <strong>Line#5 — </strong>Setting s1 and s2 as Register.getInstance() <br><strong>Line#7 — </strong>Comparing if the s1 and s2 are equals<br><strong>Line#13 — </strong>Setting the count property of s1 instance<br><strong>Line#18 — </strong>Setting the count property of s2 instance</p><p>And now let’s see the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXzXvM5VyYdj9SITmejPSA.png" /></figure><p>So far, so good! But there’s a bit trick, if you try to instantiate the Register class using new Register() it’ll work as expected, let’s see a example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c62ffb09308c9e45c92dcc77421b32cd/href">https://medium.com/media/c62ffb09308c9e45c92dcc77421b32cd/href</a></iframe><p>And here the log return:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RfHMC7BR2dJHZUHKnz35uQ.png" /></figure><p>It means, we’ve a pattern break, so let’s fix it adding a private constructor the Register class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52f9a25919e9ccfb5b256817bc922a62/href">https://medium.com/media/52f9a25919e9ccfb5b256817bc922a62/href</a></iframe><p><strong>Line#18</strong> — The private constructor that’ll prevent the class from being instantiated using a new Register() with that you probably will get: Constructor of class ‘Register’ is private and only accessible within the class declaration.</p><p>Briefly, to have a Singleton class you need:</p><ul><li>Have the constructor of the class private</li><li>A private static property to storing your class</li><li>A method to initialize and instantiate the class</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5071cfb88c33" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-meireles/design-patterns-singleton-5071cfb88c33">Design Patterns — Singleton</a> was originally published in <a href="https://medium.com/dev-meireles">dev.meireles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-Oriented Programming with TypeScript — Abstraction]]></title>
            <link>https://medium.com/dev-meireles/object-oriented-programming-with-typescript-abstraction-4dcd976c8ae2?source=rss-d60aa70b5a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dcd976c8ae2</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Gabriel Meireles]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 21:07:12 GMT</pubDate>
            <atom:updated>2022-04-04T21:07:12.122Z</atom:updated>
            <content:encoded><![CDATA[<h3>Object-Oriented Programming with TypeScript — Abstraction</h3><figure><img alt="Object-Oriented Programming with TypeScript — Abstraction" src="https://cdn-images-1.medium.com/max/1024/0*a4RYcMtFZAS0ngrp" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Abstraction?</h3><p>Abstraction is one of the concepts of Object-Oriented Programming aka OOP, it’s the capability to remove unnecessary or even complex characteristics from something aiming to keep just the crucial aspects. I know it really looks like: WTH!? But let’s exemplify and simplify it, I won’t use the car example, I promise!</p><p>How about a soda fountain machine? It might be a good example of abstraction. To get a soda from a soda fountain machine you don’t need to know that in a soda fountain machine made your drink on-the-fly when you press the dispenser tab. A pressurized carbon dioxide tank and a water pump send pressurized carbon dioxide gas and cold water to a carbonator, where it’s mixed and the gas dissolves into the water, then a bit of flavoured syrup and voilà, here’s your drink.<a href="https://wonderopolis.org/wonder/how-are-fountain-drinks-different-from-bottled-drinks#:~:text=The%20soda%20you%20get%20from,gas%20dissolves%20into%20the%20water.">[1]</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F41DjuNcaivZni%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F41DjuNcaivZni%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F41DjuNcaivZni%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/18d3c25a48d71772f1c2b2acf0822c6b/href">https://medium.com/media/18d3c25a48d71772f1c2b2acf0822c6b/href</a></iframe><p>In this case what matters for us is just the capability to push the button and wait for our drink, that’s all, so in this abstraction scenario “push this button to get a drink” is the essential characteristic. In other hand presuming you’re a engineer and there are some calls saying that the button is stuck sometimes and you need to fix it, so far just knowing how to get a drink is insufficient to fix the machine so you need to go deeply and know how a soda fountain machine works to be able to deal with that.</p><h3>Let’s code</h3><p>Still using the soda fountain machine example let’s write some code, we need to transform this machine in a class, so far what we know is: there’s a unique button that when pushed drop some soda:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b54107b17b1055ecc50265be867955e9/href">https://medium.com/media/b54107b17b1055ecc50265be867955e9/href</a></iframe><p><strong>L#4 — </strong>Creating a SodaMachine class that’s a representation of the soda fountain machine blueprint<br><strong>L#8 — </strong>Setting a doPush method that’ll drop soda when pushed<br><strong>L#13 — </strong>Using the soda constant to instantiate theSodaMachine class<br><strong>L#14 — </strong>Calling the doPush method from SodaMachine class instantiated as soda</p><p>Let’s think we still constructing our soda machine and we need to add more buttons, so in this new version our machine won’t contains just one button but now we can offer two more flavours, three in a total.<br>Taking into account that now we’ve more information about our machine, let’s assume that the flavours are: Cola, Lemon and Orange, so let’s code!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09d9c1917baed6038afe1a404e0e4ccd/href">https://medium.com/media/09d9c1917baed6038afe1a404e0e4ccd/href</a></iframe><p><strong>L#8 — </strong>Adding a ESodaFlavours enum to help the machine to identify the chosen flavour<br><strong>L#8 — </strong>Adding a flavour param for doPush method that should be a item from ESodaFlavours enum<br><strong>L#25, L#26, L#27 — </strong>Simulating three different pushed button scenarios</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fe5BASCeekXYoo%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fe5BASCeekXYoo%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fe5BASCeekXYoo%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="194" frameborder="0" scrolling="no"><a href="https://medium.com/media/3003b91f9b217ef8582d5a3cecfa593f/href">https://medium.com/media/3003b91f9b217ef8582d5a3cecfa593f/href</a></iframe><p>Our machine is almost complete, we just need to add some ice, so we’ll add a new button that’s really different from the rest, when pushed it should drop some ice cubes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/179011892cc96730acdc19cb477b6f18/href">https://medium.com/media/179011892cc96730acdc19cb477b6f18/href</a></iframe><p><strong>L#18 — </strong>Moving from doPush to dropSoda <br><strong>L#25 — </strong>Adding dropIce method to deal with ice cubes requests<br><strong>L#33, L#33 — </strong>Simulating a scenario where the user request a soda with ice</p><p>We finally have our soda fountain machine constructed and ready to release! <br>Briefly, abstraction refers to the act of representing essential aspects, omitting unnecessary characteristics, as we did previously, abstraction is an useful key-concept of OOP that helped us transform a real world machine in blueprint.</p><p>[1] — <strong>How Do Soda Fountain Machines Work? </strong>— <a href="https://wonderopolis.org/wonder/how-are-fountain-drinks-different-from-bottled-drinks#:~:text=The%20soda%20you%20get%20from,gas%20dissolves%20into%20the%20water">https://wonderopolis.org/wonder/how-are-fountain-drinks-different-from-bottled-drinks#:~:text=The%20soda%20you%20get%20from,gas%20dissolves%20into%20the%20water</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dcd976c8ae2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-meireles/object-oriented-programming-with-typescript-abstraction-4dcd976c8ae2">Object-Oriented Programming with TypeScript — Abstraction</a> was originally published in <a href="https://medium.com/dev-meireles">dev.meireles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2020–21 Transfer Window — Plotting Maps]]></title>
            <link>https://medium.com/data-science-soccer-club/2020-21-transfer-window-plotting-maps-25fbdb39c389?source=rss-d60aa70b5a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/25fbdb39c389</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[soccer]]></category>
            <category><![CDATA[soccer-analytics]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Gabriel Meireles]]></dc:creator>
            <pubDate>Mon, 21 Sep 2020 20:09:45 GMT</pubDate>
            <atom:updated>2020-09-21T20:09:45.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w6QelBtTW2md28bK" /><figcaption>Photo from <a href="https://unsplash.com/photos/V6kZMhjWveo">Unsplash</a> by <a href="https://unsplash.com/@emersonvieira">Emerson Vieira</a></figcaption></figure><h3>2020–21 Transfer Window — Plotting Maps</h3><p>Hello everyone! In this article we’ll talk about <strong>Plotting Maps</strong>, after a few days of research, reading and many attempts I came to this final article in which I cover examples not only of how to plot maps using the Plotly library but also some examples of data handling with Pandas.<br>In the <a href="https://medium.com/data-science-soccer-club/2020-21-transfer-window-data-scraping-with-python-b0ee406126f2">previous post</a> we covered how to get data from a website using the technique known as <strong>web scraping</strong>, so continuing our work, today we’ll create a way to visualize the data obtained.</p><p><a href="https://medium.com/data-science-soccer-club/2020-21-transfer-window-data-scraping-with-python-b0ee406126f2">2020-21 Transfer Window — Data scraping with Python</a></p><h4>What we’ll do?</h4><p>Using the Pandas library we’ll explore and manipulate the data to be plotted by the <strong>Plotly</strong> library. We’ll use data sheet extracted in the <a href="https://medium.com/data-science-soccer-club/2020-21-transfer-window-data-scraping-with-python-b0ee406126f2"><strong>last article</strong></a> and available on this <a href="https://gist.github.com/devmeireles/1187a3e085516e2f27a26774005d5cc2#file-players_transfer_250-csv"><strong>link</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJJDHkpEAqcTElypsmAxCA.png" /><figcaption>data sample from csv file</figcaption></figure><p>It’s important to have knowledge about the columns that we’ll work on, they are:</p><ul><li><strong>name: </strong>The player’s name</li><li><strong>position: </strong>The player’s position</li><li><strong>age: </strong>The player’s age</li><li><strong>market_value: </strong>The player’s market value</li><li><strong>country_from: </strong>The country that the player was playing</li><li><strong>league_from: </strong>The league that the player was playing</li><li><strong>club_from: </strong>The club that the player was playing</li><li><strong>country_to: </strong>The country the player will play</li><li><strong>league_to: </strong>The league the player will play</li><li><strong>club_to: </strong>The club the player will play</li><li><strong>fee: </strong>How much the club paid for the player</li></ul><p>Let’s start by importing some libraries:</p><ul><li><strong>Pandas</strong> to handle the data (Responsible for doing the magic with the data)</li><li><strong>Nominatim</strong> to pull the geo data</li><li><strong>Plotly</strong> to build the plots</li><li><strong>Pycountry</strong> to handle the ISO database</li><li><strong>Os</strong> to handle some paths</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cc3051babca9ad8e1498871bbea53af/href">https://medium.com/media/4cc3051babca9ad8e1498871bbea53af/href</a></iframe><p>Just as we created some functions to help us extract the data, we’ll create some others functions to help us handle the data, so let’s start with <strong>get_iso</strong> which should receive the country and return the <a href="https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3">ISO 3166–1 alpha-3</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b55793c136892e183e8882e8b9c68ce1/href">https://medium.com/media/b55793c136892e183e8882e8b9c68ce1/href</a></iframe><p>After that we’ve the function <strong>get_geo</strong> which receives country and type and returns the latitude and longitude of the informed country.<br>It’s certain that this function needs to be refactored:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10bdbe4a92a32a7b1e483d3248c94b6e/href">https://medium.com/media/10bdbe4a92a32a7b1e483d3248c94b6e/href</a></iframe><p>Now let’s start by reading our data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b160c71288df44c6276f8021e7386a50/href">https://medium.com/media/b160c71288df44c6276f8021e7386a50/href</a></iframe><p>And that must be the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*G9qWg0MKfyX1hJvA0nSTdA.png" /><figcaption>Result from loaded dataframe</figcaption></figure><p>So let’s apply the <strong>get_geo</strong> function to get the latitude and longitude of the departure and arrival of the transfer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bbce6169a1b2e508025a2cf29a7f4c9/href">https://medium.com/media/5bbce6169a1b2e508025a2cf29a7f4c9/href</a></iframe><p>Bearing in mind that this process tends to be time consuming, I chose to save the updated data in a new csv and load it again with pandas:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d5ba0cb38ac6557933e1c6856eb5973/href">https://medium.com/media/2d5ba0cb38ac6557933e1c6856eb5973/href</a></iframe><p>And then this must be the new dataframe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYNaXPH1xmoE83rvVBpIvg.png" /><figcaption>Result from loaded dataframe with geo data</figcaption></figure><p>After applying the <strong>get_geo</strong> function we’ll have 4 new columns:</p><ul><li><strong>lat_departure: </strong>Latitude of country of departure</li><li><strong>lon_departure: </strong>Longitude of country of departure</li><li><strong>lat_arrival: </strong>Latitude of the country of arrival</li><li><strong>lon_arrival: </strong>Longitude of the country of arrival</li></ul><p>And finally we apply the function <strong>get_iso</strong> to obtain the alpha_3 of the departure and arrival of the transfer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1999642882586c9a00a01402603d67d2/href">https://medium.com/media/1999642882586c9a00a01402603d67d2/href</a></iframe><p>After that we’ll have 2 other new columns:</p><ul><li><strong>iso_from: </strong>The ISO 3166–1 alpha-3 of country of origin</li><li><strong>iso_to: </strong>The ISO 3166–1 alpha-3 of country of arrival</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fwdNhneFSDoO19jHRVpcw.png" /><figcaption>Result from loaded dataframe with iso data</figcaption></figure><p>In the fee column we’ve some values ​​like: “Free transfer”, “Loan” or “?” for when the transfer amount wasn’t informed. We need to remove the lines that contain these values, leaving only the lines that contain integers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae8bb1518068801981ca4cede8e9b856/href">https://medium.com/media/ae8bb1518068801981ca4cede8e9b856/href</a></iframe><p>The data structure is the same, but now we’ve less information, notice that before we’d 250 rows, now we’ve 186 rows.<br>So, 64 rows were removed in which the fee column didn’t correspond with our parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFxEpSeXpXIuuxXC-N-gag.png" /><figcaption>Result from loaded dataframe without string data in fee column</figcaption></figure><p>Well, I think we’ve what we need. So let’s start plotting some graphics! Let’s start with the best sellers of this transfer window, for that we group the columns country_from and iso_from and then sum the values ​​of the fee column:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54eaec082ff1cfd00ead8885028aa770/href">https://medium.com/media/54eaec082ff1cfd00ead8885028aa770/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*nulAAaLZWTcit8C5d9LShw.png" /><figcaption>Result from loaded profits</figcaption></figure><p>Now that we know how much each country has sold in this transfer window, we can now create our first chart:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba6e841c329f91227d4b51409111ea2c/href">https://medium.com/media/ba6e841c329f91227d4b51409111ea2c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7vWoDfUng9sAlecYHuXp4g.png" /><figcaption>2020–21 Best Sellers</figcaption></figure><p>Following the same logic used previously, let’s find out who are the countries that spent the most in this transfer window:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3ec1cd52ba893d77e87ab456aa6a737/href">https://medium.com/media/d3ec1cd52ba893d77e87ab456aa6a737/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*e4nF-90yy5py-tWcJ80yrw.png" /><figcaption>Result from loaded spendthrift</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d69e8e6715f46a5aabf3712840ceb1fe/href">https://medium.com/media/d69e8e6715f46a5aabf3712840ceb1fe/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EPCclEMXatvEuWVPs5h-Q.png" /><figcaption>2020–21 Top Buyers</figcaption></figure><p>The great time has come for us to use geo columns! And now to finish, we’ll render a last map showing the “flights” of departure and arrival of transfers. So let’s start by grouping some data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd389056171172c8af0209eed6f3ea34/href">https://medium.com/media/bd389056171172c8af0209eed6f3ea34/href</a></iframe><p>This should be our result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*mJqBZ7rmou-jpbB47f7m-A.png" /></figure><p>Now let’s build our map:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bb6161cbc5a288dee09a358549350bb/href">https://medium.com/media/5bb6161cbc5a288dee09a358549350bb/href</a></iframe><p>Note that the vast majority of transfers are internal, that is, the player only changes clubs or even divisions. Another interesting point is the transfers between the countries of Western Europe, which concentrates the vast majority of transactions, besides, it is there that the Big Five clubs are located.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*60Q6wsWionutkXlZzfWwNg.png" /><figcaption>Connection Map depicting flights from all over the transfers</figcaption></figure><p>So that the reading does not become tiresome I decided to divide the data visualization in some parts. In our next step we continue to work with data visualization, we will explore everything in detail, such as clubs, players and leagues, in addition to creating interactive plots. So stay tuned to the <a href="https://medium.com/data-science-soccer-club"><strong>Data Science Soccer Club</strong></a> and thank you a lot for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25fbdb39c389" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-soccer-club/2020-21-transfer-window-plotting-maps-25fbdb39c389">2020–21 Transfer Window — Plotting Maps</a> was originally published in <a href="https://medium.com/data-science-soccer-club">Data Science Soccer Club</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2020-21 Transfer Window — Data scraping with Python]]></title>
            <link>https://medium.com/data-science-soccer-club/2020-21-transfer-window-data-scraping-with-python-b0ee406126f2?source=rss-d60aa70b5a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0ee406126f2</guid>
            <category><![CDATA[soccer]]></category>
            <category><![CDATA[soccer-analytics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-scraping]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Gabriel Meireles]]></dc:creator>
            <pubDate>Thu, 17 Sep 2020 20:15:20 GMT</pubDate>
            <atom:updated>2020-09-21T20:13:44.049Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Il3JoZVV1dlJaYDR" /><figcaption>Photo from <a href="https://unsplash.com/photos/qvBYnMuNJ9A">Unsplash</a> by <a href="https://unsplash.com/@guoshiwushuang">Michael Lee</a></figcaption></figure><h3>2020-21 Transfer Window — Data scraping with Python</h3><p>Hello there!<br>I’m really very excited to share some of the things I’ve been learning for the past few days. I’m not an expert in Python, statistics, maths or even in English, but my purpose is share with you some information about soccer and data science with Python. So without further ado, let’s start!</p><h4>What we’ll do?</h4><p>Every beginning of the season the market is heated, many transfers are made, some clubs invest heavily aiming not only at local competitions but also the desired international achievements. Our mission is to <strong>capture</strong> this information, <strong>treat</strong> it as necessary and <strong>present</strong> it through graphic representations.<br>If we put everything on a list, this is what we’ve to do:</p><ul><li>Create a script to get the latest transfer data</li><li>Create a script to obtain information (goals, assists, cards, etc.) from the respective players</li><li>Create graphic representation through the scraped data</li></ul><h4>Scraping the data</h4><p>The first step is to obtain information about the transfers and for that we use <a href="https://www.transfermarkt.com/transfers/saisontransfers/statistik?ajax=yw0&amp;altersklasse=&amp;ausrichtung=&amp;land_id=0&amp;leihe=&amp;page=1&amp;plus=1&amp;saison-id=2020&amp;spielerposition_id=&amp;transferfenster="><strong>Transfermarkt</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zq3tT-p0xwGN78846wELuQ.png" /><figcaption>Latest transfers — Transfermarkt</figcaption></figure><p>All we need is to read the information from the table and save it in a csv file and for that we’ll use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/"><strong>BeautifulSoup</strong></a>, a library responsible for pulling data out of HTML and XML files, in our case HTML. With <strong>bs4</strong> it’s possible to transform rows and columns of a table into a <a href="https://docs.python.org/3/tutorial/datastructures.html">Python list of dictionaries</a>.</p><p>Let’s start by importing some libraries:</p><ul><li><strong>Requests</strong> to make the request to the web address</li><li><strong>BeautifulSoup</strong> to pull data from HTML</li><li><strong>Csv</strong> to put the data in the csv file</li><li><strong>Re</strong> to handle regex</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d495e0a011e12a734f6fd991454b1b41/href">https://medium.com/media/d495e0a011e12a734f6fd991454b1b41/href</a></iframe><p>Now we’re going to create some functions that will help us throughout the application. Starting with <strong>data_to_csv</strong> which receives a list to save a csv output file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69496cae12426bdc09bd80033f9ffad0/href">https://medium.com/media/69496cae12426bdc09bd80033f9ffad0/href</a></iframe><p>We also have the <strong>format_text</strong> function that takes a string and remove some chars like double with spaces or escape sequences:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d106d12e181a66ef47a5eece3110fda3/href">https://medium.com/media/d106d12e181a66ef47a5eece3110fda3/href</a></iframe><p>Now a function to handle with the currency:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5df0c09ea9482ffc2e910b6a7e47f44b/href">https://medium.com/media/5df0c09ea9482ffc2e910b6a7e47f44b/href</a></iframe><p>And finally our function responsible for accessing the pages (line 10), transform the HTML in a soup object (line 11), look for an element with the <em>responsive-table</em> class (line 13), so iterate all the even and odd classes (line 16) to get the ‘tds’ or cell and then create a dictionary with the information we need (line 28), appending the var player (line 42) to the players_list (created on line 2) and finally return on line 46. Easy, right?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aeeac70e9c50f7172ac4e54ae8a29956/href">https://medium.com/media/aeeac70e9c50f7172ac4e54ae8a29956/href</a></iframe><p>Then we run the script saying that we want to browse the first 10 pages, remembering that each page displays 25 players, we’ll have 250 players in all. So, we send the dictionary to the function <strong>data_to_csv</strong> responsible for saving the data in a csv file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63afdf334718ab4e6d18e4011b7e4517/href">https://medium.com/media/63afdf334718ab4e6d18e4011b7e4517/href</a></iframe><p>And the result is this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0471d2dd94c4356870bd5ec51b1e8b6c/href">https://medium.com/media/0471d2dd94c4356870bd5ec51b1e8b6c/href</a></iframe><p>Now that we’ve the necessary data, the time has come to manipulate and display it:</p><p><a href="https://medium.com/data-science-soccer-club/2020-21-transfer-window-plotting-maps-25fbdb39c389">2020–21 Transfer Window — Plotting Maps</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0ee406126f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-soccer-club/2020-21-transfer-window-data-scraping-with-python-b0ee406126f2">2020-21 Transfer Window — Data scraping with Python</a> was originally published in <a href="https://medium.com/data-science-soccer-club">Data Science Soccer Club</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>