5 best examples of eCommerce dashboards to help you take control of your business

https://www.noupe.com/wp-content/uploads/2022/01/mark-konig-Tl8mDaue_II-unsplash-1-1024×576.jpg

Being an entrepreneur means you must keep a lot of things under control. You have to always know what is going on in sales, marketing, finance, inventory, and other aspects of your business.

Moreover, you probably use a myriad of tools to run them. Switching between a CRM, marketing automation software, Google Analytics, Accounting System and your eCommerce back-end won’t provide a clear picture of how your business is doing. 

Wouldn’t it be great to have one screen showing the most important information about your business? eCommerce dashboards are here to give you this opportunity.

What is a dashboard and why do you need it?

eCommerce dashboard is a visual representation of up-to-date data (metrics and KPIs) important for the business. It helps to analyze the main indicators to improve the results. Dashboards are different from other analytics tools because they give insights on the most vital data. Thanks to dashboards you can check the vitals of your business any time you want and not just during your monthly reports.

This becomes possible because they accumulate real-time (or near real-time) data. With the help of a well-tuned dashboard, you can quickly spot and fix problems and see if your company is effective or not. It takes less time and effort to check a dashboard than to dig into monthly reports and collect info manually. 

Dashboards provide statistics on different areas of your online store, including, but not limited to monthly sales, website traffic, and marketing campaigns. You can compare data by any period of time: days, months, or even years. 

Let’s look at the most popular examples of dashboards for eCommerce.

5 eCommerce dashboards examples

We’ve prepared five examples of dashboards that will help you run your store. Keep in mind that there are no universal solutions that can fit everyone. The best solution for you depends on the complexity and scale of your business: are you going to create a marketplace or a small online store? How many product categories and markets are you going to cover? All of this will impact the types and number of KPIs you will have to track. 

Store overview

The overview dashboard shows the performance of the store across all major areas of the business like sales, marketing, inventory, and others. This type of dashboards enables you to see the most important metrics of your business on one screen. 

Goal: to get a snapshot of your store performance.

KPI examples: 

  • Total sales
  • Sales by product, marketing channel, geography, etc.
  • Traffic
  • Average order value
  • Conversion rate
  • Repeat customer rate
  • Customer Lifetime Value

Dashboard Example: 

Store overview dashboard

Google Analytics for eCommerce

Google Analytics is the number one tool for analyzing website traffic. It also provides a lot of information which makes it difficult to digest. That is why you need a Google Analytics eCommerce dashboard that will show only the most meaningful data for your online store. 

Goal: to check your website’s most current statistics.

KPI examples:

  • Unique visitors
  • Average session duration
  • Bounce rate 
  • Time on site
  • Goal completions 
  • Traffic sources
  • Top pages
  • Top keywords

Dashboard Example: 

Google Analytics dashboard

Sales

eCommerce sales dashboard shows KPIs like total sales, as well as sales by product, marketing channel, location etc. This is a functional strategic tool that allows getting an instant overview of your sales to pinpoint any problem as soon as it occurs. It organizes the most precise and recent data related to commercial success.

Goal: to see current sales performance and compare it to your sales target.

KPI examples: 

  • Total sales
  • Sales target
  • Average order value
  • Lead conversion rate
  • Up-sell and cross-sell rates
  • Profit margin per product

Dashboard Example: 

Sales dashboard

Marketing

eCommerce marketing dashboards present vital KPIs in digital marketing to track channel and campaign results in real-time. These KPIs include traffic sources, macro and micro conversions, leads, ROI of marketing channels and campaigns, etc. The information is collected from such channels: Google Analytics, email marketing tools, CRM, social media, and others. 

Goal: to see how effective your marketing is in real-time. 

KPI examples: 

  • Traffic
  • Leads
  • Sales
  • Conversion rate
  • Conversions by channel
  • Customer acquisition cost (total and by channel)

Dashboard Example: 

Marketing dashboard

Finance

This dashboard focuses on your budget and analyzes existing assets, profit and expenses, cash flow, income, and other financial indicators. It allows you to see the current figures and financial details to get helpful insights and increase the cost-efficiency of your business.

Goal: to see the current financial state and overall profitability of the business.

KPI examples:

  • Revenue
  • Net profit
  • Gross / Net profit margin
  • Cash balance
  • Working capital
  • Cost of goods sold

Dashboard Example: 

Finance dashboard

Wrapping up

To sum up, eCommerce metrics dashboards are useful tools that help track your business performance on a daily basis. They can either provide an overview of the entire business or may cover different areas from SEO to finances. 

The fundamental advantage is that you can check your KPIs any time, not just once a month when you prepare your reports. This will help to detect and fix problems almost on the spot. Another advantage is that dashboards are visual tools that allow you to digest information easily. Additionally, they are customizable and can show the indicators which you need the most.

In this article, we shed some light on what dashboards are and why they matter. We also gave examples of dashboards that might be helpful for your eCommerce business. Give these tools a try and get a clearer picture of how your store is doing.

The post 5 best examples of eCommerce dashboards to help you take control of your business appeared first on noupe.

noupe

I don’t think this meme makes the point they want it to make

https://gunfreezone.net/wp-content/uploads/2022/01/FJgyZvLX0AIDtDM.jpeg

I’ve seen this meme posted several times online:

 

The point is always the same.  It’s not fair that the Red area is represented by eight senators and the green represented by two senators.

So the conclusion they draw is that we must abolish the Senate.

Because the Left already controls the House of Representatives, they need to attack the Senate.

I look at this and come to a different conclusion.

The population density of NYC is 27,000 per square mile.  The average for the United States is 94 per square mile.

New York City is 288 times more dense as the average.

Cities like NYC are unnatural and unsustainable.

They can’t grow enough food to feed their population or have landfill space to dispose of their garbage.

Clearly before we abolish the Senate we have to abolish the megacities.

Laracon Online Winter will be free this year!

https://laravelnews.imgix.net/images/laracon-online-winter2022.jpg?ixlib=php-3.3.1

Join us on February 9th, 2022, for this year’s Laracon Online winter edition. It will be free for everyone!

For the first time ever, we’ll be streaming Laracon for free on YouTube, allowing us to reach the entire Laravel community. This is a huge moment (and experiment) for us. Thank you to the following incredible partners for helping us achieve this!

Gold Sponsors

Silver Sponsors

Community Sponsors

If your company would like to partner for the event, we still have a few spots left.

Schedule

Here is the schedule for the day, all times are EST (GMT-4):

  • 8:55 AM – Opening – Ian Landsman
  • 9:00 AM – Actions are a Dev’s Best Friend – Luke Downing
  • 9:40 AM – Modularising the Monolith – Ryuta Hamasaki
  • 10:20 AM – Digital Nomadding in the Time of COVID – Polly Washburn
  • 10:35 AM – Typing In and Out of Laravel – Craig Morris
  • 10:50 AM – Everything Flex – Shruti Balasa
  • 11:20 AM – Dealing with Criticism – Kristin Collins
  • 12:00 PM – A Little Bit More Lambda – Aaron Francis
  • 12:40 PM – Web 3.0 and Laravel – Marcel Pociot
  • 1:40 PM – Laravel Update – Taylor Otwell
  • 2:40 PM – How to do API integrations in Laravel – Steve McDougall
  • 3:20 PM – Building Awesome Blade Components With Alpine – Caleb Porzio
  • 4:30 PM – Discovering Route Discovery – Freek Van der Herten
  • 4:35 PM – The Art of Programming – Erika Heidi
  • 4:50 PM – Using Lando for local Development – Rory McDaniel
  • 5:05 PM – The Jigsaw Challenge – Zuzana Kunckova
  • 5:30 PM – Laravel for millions and some… – Ashley Hindle
  • 6:00 PM – Keep Thinking Like a Hacker – Stephen Rees-Carter

Can’t watch it live? No problem, all talks will be recorded and available online for viewing at your convenience shortly after the conference ends.

Mark your calendar for February 9th, 2022, and join the conference for free live on Youtube! For complete details, check out Laracon Online and subscribe to the YouTube channel.

PS: If you want some sweet desktop images from the art we have them here:

Laravel News

Amazon reveals title and trailer for new ‘Lord of the Rings’ series coming to Prime Video

http://img.youtube.com/vi/uEepEyrHmtE/0.jpg

Are you ready to head back to Middle Earth? Amazon Studios revealed the title and trailer Wednesday for its highly anticipated prequel to the “Lord of the Rings” series, called “The Lord of the Rings: The Rings of Power.”

The series will debut on Prime Video on Sept. 2.

“The Rings of Power” is set in the Second Age of Middle Earth, thousands of years before the events of J.R.R. Tolkien’s “The Hobbit” and “The Lord of the Rings.”

The series “will take viewers back to an era in which great powers were forged, kingdoms rose to glory and fell to ruin, unlikely heroes were tested, hope hung by the finest of threads, and the greatest villain that ever flowed from Tolkien’s pen threatened to cover all the world in darkness,” Amazon said in its YouTube description for the trailer.

Amazon founder Jeff Bezos tweeted an image of himself holding a big slab of wood with the series title on it. “Can’t wait for you to see it,” he wrote.

IGN has behind-the-scenes details on how the title sequence was created, and it wasn’t with CGI, but rather with molten metal and a “hunk of reclaimed redwood.”

Amazon first announced that it had acquired the rights to adapt Tolkien’s work in 2017.

“’The Lord of the Rings’ is a cultural phenomenon that has captured the imagination of generations of fans through literature and the big screen,” Sharon Tal Yguado, head of Scripted Series for Amazon Studios, said in a statement at the time. 

Tolkien’s book series was named Amazon customers’ favorite book of the millennium in 1999. Director Peter Jackson’s theatrical adaptations included “The Fellowship of the Ring” (2001); “The Two Towers” (2002); and “The Return of the King” (2003). The films grossed nearly $6 billion worldwide and won a combined 17 Academy Awards, including Best Picture for “King.”

GeekWire

Holosun’s New RML Gives You Small, Lightweight Red or Green Laser Aiming Capability

https://cdn0.thetruthaboutguns.com/wp-content/uploads/2022/01/IMG_0461-scaled.jpg

Holosun RML Rail Mounted Laser
Holosun’s new RML Rail Mounted Laser

Next Post Coming Soon…▶

Holosun just introduced their new RML Rail Mounted Laser. It’s tiny and affordable and will come in both red and green laser versions. The RML will come in five models with MSRPs ranging from $105 to $162 and is expected to hit stores in March or April.

Here’s their press release . . .

Lasers are becoming invaluable to verify an accurate and effective aim, especially in low-light environments. Pistols and rifles fixed with lasers have been shown to improve fast target acquisition. With the growth of red dot optics, lasers have fast been growing in the industry as an alternative to mounted optics. Not only does this help to improve users’ response time, but it also makes a potential Point of Impact clear.

Holosun RML Rail Mounted Laser
Holosun is known for optics and lasers. This year, Holosun releases the RML (Rail-Mounted Laser). The RML comes in at a very manageable 1.97″×1.18″×0.91″ and 1.3 ounces. Made with a durable polymer housing, the RML is IPX8 rated for water and dust resistance. Additionally, Holosun tests each unit to 2,000G shock resistance. This guarantees that the RML is suited for use in extreme environments.

The RML is available in either a red or green laser version, both of which are class 3R and <5mW output power. The RML package includes one CR1/3N lithium battery. The laser can be adjusted by 4MOA per click and can travel a total of +/-60 MOA. The rate of travel makes it ideal for a primary or even secondary zero, providing an alternate distance point of aim from iron sights or a pistol mounted optic.

Holosun RML Rail Mounted Laser
With many features, it is easy to see why the RML is a strong contender. Holosun has made it easy to utilize the laser in multiple roles with multiple color options. For the hiker who carries a defensive pistol, the uniformed officer that relies on an alternate color laser and red dot, and everything in between, the RML fills their needs.

Specifications:

  • 520nm Green or 635nm Red, class 3R laser
  • Cr1/3N removable battery
  • Durable Polymer housing
  • 4 MOA adjustment per click
  • +/- 60 MOA laser W&E travel range
  • IPX8 water & dust resistance
  • 2000G vibration resistance
  • Dimensions: 1.97×1.18×0.91
  • Weight: 1.8oz

 

Next Post Coming Soon…▶

The Truth About Guns

10 Fun Linux Command-Line Programs You Should Try When Bored

https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2022/01/children-having-fun-with-linux-commands.jpg

The Linux terminal is a powerful utility. You can use it to control the whole system, crafting and typing commands as you go about doing your everyday tasks. But it can quickly become overwhelming to keep staring at a command line and carry on with your work.

Lucky for you, the terminal is also a source of fun. You can play around with commands, listen to music, and even play games. Although expecting a great deal of entertainment from a window full of commands would be carrying it too far, you can find utilities to bind some time when bored.

Here are some fun and entertaining commands every Linux user should try at least once.

1. CMatrix

Starting off the list with a fun tool every Linux user loves, CMatrix is a command-line utility that generates the classic “The Matrix” animation from the popular movie franchise of the same name. You can expect to see some great animations in different colors that you also get to customize.

Albeit CMatrix uses regular fonts instead of the original Japanese characters, you’ll definitely enjoy every moment you spend with the tool. Either use it as your desktop screensaver or include the program in your window manager rice screenshots, the choice is yours. You can even go to the extremes and set up a CMatrix server on a laptop that runs the program 24/7.

MAKEUSEOF VIDEO OF THE DAY

To install Cmatrix on Debian-based distros like Ubuntu:

sudo apt install cmatrix

On Arch Linux and its derivatives:

sudo pacman -S cmatrix

On RHEL-based distros like Fedora:

sudo dnf install cmatrix

2. cowsay

What does the cow say? Definitely, not just “moo.”

cowsay is an ASCII-art-based command-line utility that displays the specified input with a neat ASCII cow art. While there’s not much to this program, you can use it as a Bash prompt by invoking the program with random quotes whenever you launch a terminal instance.

cowsay "Mooooo"

To install cowsay on Debian and Ubuntu:

sudo apt install cowsay

On Arch Linux:

sudo pacman -S cowsay

On Fedora, CentOS, and RHEL:

sudo dnf install cowsay

3. sl

Everyone loves trains, especially steam locomotives. The Linux utility sl brings your favorite steam locomotive to your desk, using the terminal of course.

Running the sl command is very simple.

sl

Installing sl on Ubuntu and Debian is easy.

sudo apt install sl

Similarly, on Arch-based distributions:

sudo pacman -S sl

On Fedora, CentOS, and RHEL:

sudo dnf install sl

4. FIGlet

Have you ever seen a Linux terminal with beautifully crafted ASCII art at the top? You can achieve the same results using FIGlet, a command-line tool that converts user input into ASCII banners.

Unlike some other ASCII art generators, FIGlet doesn’t have a character limit, which is what sets it apart. You can create ASCII arts of unlimited length with the tool, although the characters might break if you supply lengthier strings.

FIGlet uses the following command syntax:

figlet "Your string here"

You can install FIGlet on Debian/Ubuntu using:

sudo apt install figlet

To install FIGlet on Arch-based distributions:

sudo pacman -S figlet

On Fedora, CentOS, and RHEL:

sudo dnf install figlet

5. fortune

Want to read a quote? Maybe something funny, or perhaps an educational message? The excitement is there every time you run fortune, as you don’t know what’s going to hit you next. fortune is a Linux utility that returns random messages and quotes on execution.

fortune

It’s easy to get engrossed in the command, reading the entertaining (mostly funny) quotes that fortune outputs. The best thing about the tool? You can pipe it with cowsay and similar programs to produce an engaging Bash prompt for yourself.

cowsay | fortune

To install fortune on Ubuntu/Debian:

sudo apt install fortune

On Arch Linux and similar distributions:

sudo pacman -S fortune-mod

Installing fortune on RHEL-based distros like Fedora and CentOS is easy as well.

sudo dnf install fortune-mod

6. xeyes

If you are someone who likes to have a pair of eyes on you every time you need to get something done, xeyes might be the best Linux tool for you. Literally, xeyes brings a pair of eyes to your desktop. The best part? The eyeballs move depending on your mouse pointer’s position.

Launching the program is easy. Simply type xeyes in the terminal and hit Enter. By default, the position of the eyes will be the top left, but you can easily change it using the -geometry flag.

On Ubuntu and Debian-based distros, you can install xeyes with APT.

sudo apt install x11-apps

To install xeyes on Arch-based distros:

sudo pacman -S xorg-xeyes

On Fedora, CentOS, and RHEL:

sudo dnf install xeyes

7. aafire

Want to make your Linux desktop lit? You need aafire. It is a terminal-based utility that starts an ASCII art fire right inside your terminal. Although you won’t physically feel the heat aafire brings to the table, it’s definitely a “cool” Linux program to have on your system.

To install aafire on Ubuntu and Debian:

sudo apt install libaa-bin

On Arch Linux and its derivatives:

sudo pacman -S aalib

On Fedora, CentOS, and other RHEL-based distros:

sudo dnf install aalib

8. espeak

Have you ever wanted your Linux desktop to speak, exactly what you want it to? espeak is a text-to-speech utility that converts a specified string to speech and returns the output in real-time. You can play around with espeak by invoking the command with song lyrics or movie dialogues.

For the test run, you can try specifying a basic string first. Don’t forget to turn up your desktop’s speaker volume.

espeak "Hello World"

You can also change the amplitude, word gap and play around with the voices with espeak. Writers can use this tool to transform their words into speech, making it a perfect tool to assess the content quality.

On Ubuntu/Debian:

sudo apt install espeak

You can install espeak on Arch Linux from the AUR.

yay -S espeak

On Fedora, CentOS, and RHEL:

sudo dnf install espeak

9. asciiquarium

For those who wish to own an aquarium someday, here’s your chance. As the name aptly suggests, asciiquarium creates a virtual aquarium inside your terminal using ASCII characters.

The fishes and the plants are colorized and that’s what makes them come to life, leaving the dull terminal screen behind. You also get to see ducks swimming in the water occasionally.

To install asciiquarium on Ubuntu and Debian:

sudo add-apt-repository ppa:ytvwld/asciiquarium
sudo apt install asciiquarium

On Arch-based distributions:

sudo pacman -S asciiquarium

Installing asciiquarium on RHEL-based distros is also easy.

sudo dnf install asciiquarium

10. rig

Want to quickly generate a fake identity for some reason? rig is what you need. Being a command-line utility, it returns output in an easy-to-read manner, for both users and computers. You can implement the functionality of rig in scripts, to test functions that require user information in bulk.

To install rig on Ubuntu and Debian:

sudo apt install rig

On Arch-based distributions:

yay -S rig

On RHEL-based distros like Fedora and CentOS:

sudo dnf install rig

Having Fun With the Linux Command Line

All the tools mentioned in the above list will guarantee you a moment of fun amidst the busy life that we’re all living. You can either install these utilities to simply play around with, or you can make something productive out of them by using them in your code.

Whatever the practical applications are, Linux programs always deliver what you expect them to. There are several other software and applications that every Linux user should know about.

The Best Linux Software and Apps

Whether you’re new to Linux or you’re a seasoned user, here are the best Linux software and apps you should be using today.

Read Next

About The Author

Deepesh Sharma
(108 Articles Published)

Deepesh is the Junior Editor for Linux at MUO. He writes informational guides on Linux, aiming to provide a blissful experience to all newcomers. Not sure about movies, but if you want to talk about technology, he’s your guy.

More
From Deepesh Sharma

Subscribe to our newsletter

Join our newsletter for tech tips, reviews, free ebooks, and exclusive deals!

Click here to subscribe

MUO – Feed

Define a Route Group Controller in Laravel 8.80

https://laravelnews.imgix.net/images/laravel8.jpg?ixlib=php-3.3.1

The Laravel team released 8.80 with the ability to define a route group controller, render a string with the Blade compiler, PHPRedis serialization and compression config support, and the latest changes in the v8.x branch.

Specify a Route Group Controller

Luke Downing contributed the ability to define a controller for a route group, meaning you don’t have to repeat which controller a route uses if the group uses the same controller:

1Route::controller(PlacementController::class)

2 ->prefix('placements')

3 ->as('placements.')

4 ->group(function () {

5 Route::get('', 'index')->name('index');

6 Route::get('/bills', 'bills')->name('bills');

7 Route::get('/bills/{bill}/invoice/pdf', 'invoice')->name('pdf.invoice');

8 });

Render a String With Blade

Jason Beggs contributed a Blade::render() method that uses the Blade compiler to convert a string of Blade templating into a rendered string:

1// Returns 'Hello, Claire'

2Blade::render('Hello, ', ['name' => 'Claire']);

3 

4// Returns 'Foo '

5Blade::render('@if($foo) Foo @else Bar @endif', ['foo' => true]);

6 

7// It even supports components :)

8// Returns 'Hello, Taylor'

9Blade::render('<x-test name="Taylor" />');

PHPRedis Serialization and Compression Config Support

Petr Levtonov contributed the ability to configure PHPRedis serialization and compression options instead of needing to overwrite the service provider or define a custom driver.

The PR introduced the following serialization options:

  • NONE
  • PHP
  • JSON
  • IGBINARY
  • MSGPACK

And the following compressor options:

These options are now documented in the Redis – Laravel documentation.

Release Notes

You can see the complete list of new features and updates below and the diff between 8.79.0 and 8.80.0 on GitHub. The following release notes are directly from the changelog:

v8.80.0

Added

  • Allow enums as entity_type in morphs (#40375)
  • Added support for specifying a route group controller (#40276)
  • Added phpredis serialization and compression config support (#40282)
  • Added a BladeCompiler::render() method to render a string with Blade (#40425)
  • Added a method to sort keys in a collection using a callback (#40458)

Changed

  • Convert “/” in -e parameter to “” in Illuminate/Foundation/Console/ListenerMakeCommand (#40383)

Fixed

  • Throws an error upon make:policy if no model class is configured (#40348)
  • Fix forwarded call with named arguments in Illuminate/Filesystem/FilesystemAdapter (#40421)
  • Fix ‘strstr’ function usage based on its signature (#40457)

Laravel News

A comprehensive guide on how to design future-proof controllers: Part 1

https://hashnode.com/utility/r?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1642053183825%2FTrLri6Qo6.jpeg%3Fw%3D1200%26h%3D630%26fit%3Dcrop%26crop%3Dentropy%26auto%3Dcompress%2Cformat%26format%3Dwebp%26fm%3Dpng

Introduction

When you are still in that learning phase with any technology, your focus is to make your app work, but I think the exponential progress starts coming when you begin to ask yourself “How can I make this better?”. One simple principle that you can immediately apply to your existing or new codebase for cleaner and more maintainable code is the Separation of Concerns principle.

Most of the server-side codebases I have come across have controllers that contain code specifying the real-world business rules on how data can be created, stored, and changed on the system. If you want to learn how to build controllers that are clean, concise, and easily maintainable, then this series is for you.

What you will learn after reading this article

  1. You will have a solid understanding of the Separation of concerns principle

  2. You will be able to identify the major steps involved in the lifecycle of a request on the server-side

  3. You will understand the role of the controller on the server side. This will ensure that the lines of code present in your controller functions are the ones that absolutely need to be in the controller

Prerequisites

  1. Understanding of client-server architecture
  2. Familiarity with model-view-controller architecture
  3. A basic understanding of Object-Oriented Programming

With all that out of the way, let’s move 🚀

Understanding Separation of concerns

What is a concern?

A concern is a section of a feature or software that handles a particular functionality in the system. A good example of a concern in a well-designed backend system is request validation, which means there is a part of the code that accepts the data coming from the client to make sure all the information is valid or at least in the right format before sending it to the other parts of the system.

What does the term Separation of concerns mean?

Since we know what a concern is, understanding the idea behind the Separation of concerns will not be difficult. Separation of concerns promotes the idea of building software in such a way that our code should be broken down into separate components or layers such that each layer handles a specific concern. An example is a feature that retrieves data from the database and then formats the data based on the client’s request. Placing both logic in the same function is a really bad idea since retrieving data from the database is a specific concern, then formatting the retrieved data is another concern.

Lifecycle of a request on the server

I have worked on building many backend systems that provide services to clients and many of them usually follow a similar pattern with 3 major steps which are mainly.

  1. Request validation: This refers to the part of your code that ensures that the data sent by a client is in a valid and acceptable format. A simple example is making sure that a value sent from the client as an email is actually a valid email address.
  2. Business logic execution: This is the section of your codebase that contains the code that enforces real-world business rules. Let’s use an app that allows a customer to transfer money from one account to another. A valid business rule is that you cannot transfer an amount that is greater than your current balance. For this app to work properly, there has to be a section of your code that compares the amount you are trying to transfer and your current balance and makes sure the business rule is obeyed. That is what we refer to as business logic.
  3. Response formatting and return:This refers to the section of your codebase responsible for making sure the data returned to the client after business logic execution is properly formatted and well presented. eg JSON, XML

Backend receives request.png

I have come across a lot of codebases that perform these three steps using a single function or method, where line 10 to 15 handles request validation, line 16 to 55 handles all the business logic with long if-else statements, loops, etc, then line 56-74 formats the response based on certain conditions, and finally, line 75 returns the data to the client. That’s about 65 lines of code in a single function! That is a ticking time bomb waiting to explode when a new engineer joins the team or when you come back to add more changes to the code.

Understanding the role of the controller in the backend request lifecycle

Imagine we have 3 tasks involving the same feature.

  1. Fix a bug in request validation
  2. Change the way data is retrieved from the database (use Eloquent ORM instead of raw queries)
  3. Add extra meta-data to the response returned to the client

If our controllers are designed in a way where each method contains all these three major steps involved in fulfilling a request on the server-side, then the flow looks something like the image below

Backend receives request 1.png

Handling these tasks become a nightmare because everyone in the team will be modifying the same function, and good luck merging all these changes without the need to resolve merge conflicts 🙄.

So, what exactly should the controller do?

The controller should serve as a delegator, meaning that the controller accepts a request with the associated data from the client, then the controller should assign the different tasks involved in fulfilling the client’s request to different parts of the codebase, then finally, the controller sends a proper response (success or failure) to the client depending on the result of the executed code.
I have illustrated this using the image below.

controller delegator.png

If our controllers are built this way, making changes will be incredibly easy, bugs will be easy to trace and the responsibility of each class and other classes it depends on to fulfill its tasks will be immediately visible even to someone looking at the code for the first time.

There is more juicy stuff to come 😋

Like I said at the beginning of the article, this is going to be a series because there is a lot of information to digest and I want to make sure you can remember a lot after reading each article. I want to separate the concerns you know 😂, so that this article does not become massive like the controllers we will be refactoring starting from the next part. If you didn’t get that joke, then maybe next time.

In the next article, Part 2. We will be refactoring a controller function with a specific focus on the Request validation concern. We will build a Request validator class and abstract all the logic involved in validating the client’s request away from the controller. I will be using Laravel in the rest of the series.

Quick Recap

  1. Separation of concerns is simply a concept that promotes the idea that you should always look at your code to identify the different functionalities involved, and think of how you can break down the code into smaller components for clarity, easy debugging, and maintenance among other benefits.
  2. All the logic involved in fulfilling a client’s request on the server-side should not be in a single location, like a controller.
  3. The controllers should serve as classes that delegate tasks to other parts of the codebase and get’s back a response from those other parts. Depending on the response received by the controller, the controller decides if the response to send back to the client should be a success or failure response.
  4. More code might be involved when trying to break down a feature into smaller components but remember, it pays off in the long run.

It’s a wrap 🎉

I sincerely hope that you have learned something, no matter how small, after reading this. If you did, kindly drop a thumbs up.

Thanks for sticking with me till the end. If you have any suggestions or feedback, kindly drop them in the comment section. Enjoy the rest of your day…bye 😊.

Laravel News Links