megacolorboy

Abdush Shakoor's Weblog

Writings, experiments & ideas.

Create a symbolic storage link

When using Laravel, the public directory is used for files that are publicly accessible. By default, it's stored in local and often stored in this storage/app/public directory. You can make it easily accessible by using the following command:

php artisan storage:link

Once, it has been created, you can use access those files using the public_path or asset methods.

<?php
echo public_path('images/sample_1.jpg');
echo asset('images/sample_2.jpg');
?>

Symbolic storage link in shared hosting

If you're hosting a laravel project via cPanel, chances are that it could be a shared hosting server and that means you can't really use php artisan storage:link for this. But don't worry, there's another way to this. Just follow the steps below:

1. Create a symlink

In your public_html/public directory, remove the storage folder. Next, create a symlink.php file in your public_html directory and add the following code:

<?php
$targetFolder = $_SERVER['DOCUMENT_ROOT'].'/storage/app/public';
$linkedFolder = $_SERVER['DOCUMENT_ROOT'].'/public/storage';
symlink($targetFolder, $linkedFolder);
echo "done";
?>

2. Create a custom route to access storage

Alright, this is kind of a hack but it works extremely fine. Just add the following route in your routes/web.php file:

<?php
Route::get('/storage/anyfolder/{filename}', function($filename){
    // Your folder path
    $folder_path = storage_path('app/public/anyfolder/'.$filename);

    // check if the file exists
    if(!File::exists($folder_path)) {
        abort(404);
    }

    $file = File::get($folder_path);
    $type = File::mimeType($folder_path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
})
?>

Now, you can access your images or any other assets easily using:

<?php
asset('storage/anyfolder/'.$filename)
?>

Hope this helps you out!

View battery status

This comes in handy if you're using the terminal in full screen but still want to know your battery life. Just type the following:

upower -i /org/freedesktop/UPower/devices/battery_BAT0

View hardware info

Want to check the specs of your system? Just type this:

lshw

Too long? Then type this for a shorter version:

lshw -short

Zip a file

This comes in handy especially whenever you want to download multiples files from a server or take backups.

zip [option] output_file input1 input2

For example: if you want to zip an entire directory with it's file contents, just do this:

zip -r myfiles.zip folder/

Writing a book on how to build ReactJS applications

I'm challenging myself to write a book on how to build simple applications using ReactJS

Over the past few months, I've been spending some of my free time to learn ReactJS and I've got to say, I really like it and got a hang of it after lots of trials and errors.

Just to make it clear, I didn't become a ReactJS expert or something but I figured that writing a book on something that you've learnt would help you understand the material much more deeper.

And since I do believe in it, I decided to challenge myself to write a book on it.

What's the aim of the book?

I aim to cover the fundamentals and concepts of ReactJS using a progressive and an example-driven approach. You know like on how to write reusable UI components, handle user events and interactions and managing state and props of a component.

By the end of this book, the reader will have solid understanding of React's concepts and be able to build cool applications using it.

When's it going to be released?

Honestly, I didn't plan on the size of the book yet but the practical content for it i.e. the actual code and applications are ready. I aim to release it somewhere around late April 2020.

Are you planning to monetize it?

Umm, nope! I believe that knowledge should be accessible for everyone and I plan on making the book open source, so that it can get updated as per the latest changes.

Conclusion

I know it's a short article but I feel like I wanted to challenge myself with a small goal for this year.

Let's see how it goes!

Using Laravel events and listeners in your application

Sharing my experiences of using events and listeners in my Laravel application.

Recently, I have started learning Laravel and now, I'm building an application for my new company using this amazing framework.

My senior developer was curious and thought of having a conversation with me that went like this:

Senior dev: Hmm, can I have a look at your code?

Me: Oh sure, here take a look.

Senior: (Goes through project file structure)

Senior: So, have you ever thought of using events in your application?

Me: Yeah, I wrote a custom JavaScript file to handle and fire events on the client-side like validating the forms and passing async requests to the server.

Senior: Hmm, that's okay but I'm talking using events in Laravel.

At this point, I was pretty clueless and I didn't know what the heck was going on. Events in PHP? I mean, I know about it in JavaScript because of it's event-driven architecture that we are all familiar with. But in PHP? I didn't know that.

Still confused, he proceeds to explain about it's concepts in an abstract manner and thanks to him, it induced my curiosity by asking myself: What's the deal in between using events over function calls using a route on a standard controller?

In today's article, I'll be talking about why and when to use events over function calls using Laravel in your application.

What's an event?

An event is a piece of reusable logic stored somewhere in your application that has a set of listeners waiting to be executed, if triggered.

Let's say, you have a simple CRUD application that involves user registration. Whenever a user registers, you may want to perform certain actions, such as:

  • Adding them into your mailing list
  • Confirmation of account

You can add more but this is just to give you an idea. Let's see take a look at two different approaches:

  1. Functional
  2. Events and Listeners

Functional

If you're using an MVC framework (Laravel, in our case), you'd do this in a controller with a bunch of methods like so:

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;

class UserController extends Controller {
    public function index() {
        // insert code to view users page
    }

    public function create(Request $request) {
        $arr = [
            'username' => $request->username,
            'email' => $request->email,
            'password' => bcrypt('something')
        ];

        $user = User::create($arr);

        $this->sendConfirmationEmail($user);
        $this->subscribeToMailingList($user);
    }

    // Send confirmation email to user
    private function sendConfirmationEmail($user) {
        // insert code
    }

    // Subscribe user to mailing list
    private function subscribeToMailingList($user) {
        // insert code
    }
}
?>

This is approach is self-contained and simple to follow but you're also adding in a lot of responsibility to your controller.

Not only that, what if the user wants to register from another place in your application, in that case, you'll have to duplicate your logic in multiple places.

Events and Listeners

Using this approach, you can split this into Event and Listener files in your application.

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\User;

class UserController extends Controller {
    public function index() {
        // insert code to view users page
    }

    public function create(Request $request) {
        $arr = [
            'username' => $request->username,
            'email' => $request->email,
            'password' => bcrypt('something')
        ];

        $user = User::create($arr);

        // Emit event
        event(new UserRegistered($user));
    }
}
?>

This is how your UserRegistered event would look like:

<?php
namespace App\Events;

use Illuminate\Queue\SerializeModels;
use App\User;

class UserRegistered {
    use SerializesModels;

    public $user;

    public function __construct(User $user) {
        $this->user = $user;
    }
}
?>

And this is how your SendConfirmationEmail listener would look like:

<?php
namespace App\Listeners;

use App\Events\UserRegistered;

class SendConfirmationEmail {

    public function __construct(User $user) {
        // insert code
    }

    public function handle(UserRegister $event) {
        // insert code
    }
}
?>

Using this approach, you can use the UserRegistered event anywhere you wanted in your application. No matter what happens, it will trigger the same actions as it was intended to do so. If you want to add a new functionality, create a new listener and register it with the event in your EventServiceProvider file like this:

<?php
protected $listen = [
    'App\Events\UserRegistered' => [
    'App\Listeners\SendConfirmationEmail',
    ],
];
?>

If you follow this approach, your logic complexity is toned down and the controller will have less responsibility.

Why use events and listeners over function calls?

Just like this answer that I found on StackOverflow question regarding events and listeners over calling functions:

You might not be in control of the code that's doing the calling. Or even if you are, you don't want to introduce dependencies into that code.

Think about it, what if you built an API or library that you want people to use but don't want them to modify the source code. Instead, you could provide a documentation that states specific events are raised under specific circumstances, in turn, they can write code that responds to such events.

I'm sure that there are more examples as to where this methodology might be applied.

When to use it?

Truth be told, it depends. If you have a simple application, then a functional approach is all you need but it's a larger and more complicated application, using Events and Listeners can be a better option.

Conclusion

Please note, I'm not an expert at this topic as I'm still learning and I thought of sharing what I had learnt. If you have any suggestions or thoughts, please share it with me on Twitter or send me a message to my inbox.

Hope you liked reading this article.

Stay tuned for more.

Extras

The Circle Packing Algorithm

Implemented a mathematically beautiful generative pattern that looks deceivingly complex to the human.

Beautiful, isn't it? It might look complex but it's mathematically quite impressive. Making this pattern wasn't hard but it definitely took a lot of trial and error to get it right and honestly, I don't really know if it's this is the most efficient way to generate this pattern.

This article isn't a tutorial but rather, I'll be talking about the algorithm itself. However, you can check out the source code in my GitHub repository.

How it works?

In order to achieve that "stacked" effect, there are two things to keep in mind:

  1. Generate circles with a random radius
  2. Look for collisions with other circles

The logic is quite similar to the Overlapping Rectangles problem except this is done with circles.

Generate circles with dynamic radius

This method will help generate valid circles with a random radius. Circles that don't overlap or collide with other circles are considered to be valid.

// Generate a valid circle
const generateCircle = () => {
    let newCircle;
    let isValidCircle = false;

    for(let i=0; i<attempts; i++) {
        newCircle = {
            x: Math.floor(Math.random() * width),
            y: Math.floor(Math.random() * width),
            radius: minRadius
        };

        if(checkForCollision(newCircle)) {
            continue;
        }
        else {
            isValidCircle = true;
            break;
        }
    }

    if(!isValidCircle) { return; }

    for(let i=minRadius; i<=maxRadius; i++) {
        newCircle.radius = i;
        if(checkForCollision(newCircle)) {
            newCircle.radius--;
            break;
        }
    }

    circles.push(newCircle);
    drawCircleOnCanvas(context, newCircle, colors[Math.floor(Math.random() * colors.length)]);
}

Look for collision with other circles

Thanks to some online research, I was able implement the Euclidean Distance equation that helped with calculating the distances between each circle and detect for collisions. Along with that, I also found another article on Touching Circles that was quite useful.

These are the formulas used to detect the collision:

  1. Find the distance between two centres \[ AB = \sqrt{ (x2 - x1)^2 - (y2 - y1)^2} \]

  2. Calculate the radii of both circles. \[R = r1 + r2\]

If the radii is greater than or equal to the euclidean distance of both circles, then it's a valid circle with no collisions.

// Check for collision in a canvas
const checkForCollision = (newCircle) => {

    let x2 = newCircle.x;
    let y2 = newCircle.y;
    let r2 = newCircle.radius;


    // Determine the euclidean distance between two circle
    // using Pythagorean Theorem.

    // Refer to: 
    // https://en.wikipedia.org/wiki/Euclidean_distance

    for(let i=0; i<circles.length; i++) {

        let otherCircle = circles[i];
        let r1 = otherCircle.radius;
        let x1 = otherCircle.x;
        let y1 = otherCircle.y;
        let xx = ((x2 - x1) * (x2 - x1));
        let yy = ((y2 - y1) * (y2 - y1));
        let radii = r2 + r1;
        let euclidDistance = Math.sqrt(xx + yy);

        if(radii >= euclidDistance) {
            return true;
        }
    }

    // Check collision on top
    if(x2 + r2 >= width || 
        x2 - r2 <= 0) {
        return true;
    }

    // Check collision on bottom
    if(y2 + r2 >= width || 
        y2 - r2 <= 0) {
        return true;
    }

    //else return false
    return false;
}

Conclusion

I'm thinking of implementing more generative patterns like Triangular Mesh and Piet Mondrian's Red, Blue and Yellow composition.

Hope you liked reading this article.

Stay tuned for more!