0

I Tried Automating My Files & Folders With PHP For The First Time

 2 months ago
source link: https://medium.com/@ajay_613/i-tried-automating-my-files-folders-with-php-for-the-first-time-4172a0af22b5
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
1*ALxDTY3PTadZeDj_0goNmA.png

I Tried Automating My Files & Folders With PHP For The First Time

Open up my Desktop or Downloads folder on any given day, and I can guarantee you that it’s going to be filled with random screenshots of websites, job descriptions, WhatsApp conversations (sometimes), CVs, quotations, invoices, service agreements, and a whole bunch of other work related stuff.

I’m sure my use of words like job descriptions or CVs in the 1st paragraph would have given you some clue as to what I do. If it hasn’t, here’s what I do — I work as a tech recruiter in a startup.

1*xoPq-aAL19vpFXGIaH4K7Q.png

How my desktop & downloads look at the end of a normal workday

And part of my job involves downloading “stuff”, frequently. And by frequently, I mean very frequently.

This results in my Desktop & Download folders getting very bloated, clumsy and messy. Much like the code I write a lot of the times.

It would be nice to keep clean. Organised. Well structured.

But doing this manually every other day or every other week would get very time consuming, and straight up annoying.

That’s why I decided to automate this whole process of cleaning up my folders with PHP (the language I used to code with back in the day).

Here’s how it went.

The Game Plan

0*M24acq7dvZOrbxg7

Most of my pet projects never see the light of day cause of scope creep. To avoid that from happening this time around, I decided to follow this game plan:

  • Setup the project
  • Only write the basic logic sequentially in an index.php file. This way, I don’t get bogged down with coming up with method names, code structure, etc.,
  • Only if there’s time, focus on the “bonus” aspects a.k.a refactoring, and make the code more reusable. Else skip.

Setting up the project

0*_cXAc6PB0pFct-K5

These are the only steps I took to get things up and running:

Basic Logic

0*WgtrOVOtUYQeGksG

The idea here is to write code just to get things working. The code doesn’t have to be super clean or well architected, it just needs to get the job done.

Here’s how I tackled the challenge at hand:

1. List out all of the items in a Source directory

$sourceDir = rtrim("/Users/ajay/Desktop", "/");
$targetDir = rtrim("/Users/ajay/Desktop/Screenshots", "/");$dirItems = scandir($sourceDir); // Built-in method to list the items in a directory

2. Loop through the directory’s items, and filter items out based on a criterion

To keep things simple, I started out with the first option, and then added the rest as I went along.

// 1. Filter out items based on a search term
str_contains(strtolower($fileName), strtolower($searchTerm))// 2. Filter out only directories or the inverse
is_dir('/path/to/' . $fileName) == true// 3. Filter based on extension
pathinfo($fileName, PATHINFO_EXTENSION) == $fileType

3. Create the target directory if doesn’t exist

if (!is_dir($targetDir)) {
return mkdir($targetDir) ?: exit("Failed to create the directory");
}

4.Loop through the filtered directory items, and move them to the target directory

$sourcePath = $sourceDir . '/' . $fileName;$targetPath = $targetDir . '/' . $fileName;echo "Moving $sourcePath to $targetPath \\n";rename($sourcePath, $targetPath); // built-in method to move files / folders around

If you’d like to view the first version of the code I wrote (a.k.a index.php), click here.

The code I wrote in steps 1–4 was decent enough to get things working. However, it was also limiting because things were hardcoded, and I would’ve had to make different copies of the same script if I wanted to use it to clean up files in the other folders.

Bonus

0*jx-VvxP6YcO2JVUu

Now that I have a basic script that’s working, I can spend time to make it better and reusable. Here’s how I tackled this:

1. Refactor the logic from index.php into a separate class.

I created a class called MoveFilesToTarget with a static method that accepts the source, target, etc., variables. This way, I can reuse the functionality anywhere

class MoveFilesToTarget 
{
protected $sourceDir, $targetDir, $dirItems, $fileTypes; protected $needle; protected $ignoreDirectories; public function __construct ($sourceDir,
$targetDir,
$fileTypes = '',
$needle = ''
)
{
//
}
}

2. Read the source, target details from a config file.

This way, I can just define multiple rules in a single place, and the whole thing runs as expected.

config.php

<?php return [
'desktop_screenshots' => [
'sourceDir' => '/Users/ajay/Desktop',
'targetDir' => '/Users/ajay/Desktop/screenshots',
'fileTypes' => 'png',
'needle' => 'screenshot' // search term
],
];

Somewhere else in your code, read the values from the config.php, and loop through them accordingly.

$config = require 'config.php';

3. Created an alias in the .bash_profile file

This way, I can run the command “cf” in my terminal any time I want to quickly clean things up.

alias cf="php /Users/ajay/projects/folder-automation/index.php"

4. Add the alias to a scheduler

Seems like this step of the solution wouldn’t be as straightforward as I hoped it to be.

Based on my research, I would need to create a daemon that’s launchd compliant to make sure that my script executes periodically.

My gut tells me that creating this daemon, and debugging it is going to take a while, so I’ll save that effort for another time.

The End Result

1*WvmNsOoVnDvcAokF1qDLAw.gif

The script in action…

Ok think I need to add a rule in the config to handle .gifs and .mp4s. Other than that though, the script works like a charm.

Want to have a look at the final codebase? Here ya go. Click here.

Overall Development Experience

If I was new to PHP, getting this off the ground would’ve been a major challenge.

Mainly because the documentation on the PHP website isn’t easy to figure out. And I’m saying this as a somewhat experienced Laravel / PHP developer.

Also, I couldn’t find any examples of how to structure a PHP project specifically for a command line utility. So to avoid spending too much time on researching best practices, I just decided to get to work by creating an index.php file.

Maybe this isn’t a bug. It’s a feature.

Low key, I’m also disappointed that I couldn’t figure out the right way to schedule a script on a Mac in time. I’ll circle back to this another time.

For now, I’ll make good use of the alias to clean my folders up any time I see them getting out of control. Who knows? Maybe I don’t need the scheduler after all…

Also Read: I Built a Chrome Extension to Instantly Find eToro’s Stocks on FINVIZ’s Stock Screener

If you like this article, and would like to see similar content from me do follow me on Medium.com to stay updated :)

Also if you enjoy my work and you’d like to support what I do, you could consider buying me a coffee here.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK