A better way to schedule commands

Avoid magic strings

Joel Clermont
Joel Clermont
2024-04-03

Over the years, I've built up an aversion to "magic" numbers and strings in code. Any time I see a -1 or the string 'ok', I just know that's going to cause trouble down the road.

At a minimum, it requires some special context to know what that -1 means. This usually could be in the form of a comment or a descriptive variable name.

It also hinders static analysis, especially when that magic string refers to another piece of code. This is one reason why enums were such a nice addition to PHP. They give us a tool to encapsulate some of these values with special meaning.

Laravel has progressively moved away from magic strings. For example, we can now define routes by using the ::class keyword.

One place I still see magic strings used with regularity is in scheduling commands. Each command has a string-based signature, which we can use when running the command manually with php artisan.

But we don't need to use that when scheduling commands. Laravel supports use of the ::class keyword here as well:

$schedule->command(YourCommandClass::class)->daily();

It's a tiny change, but now when you're hunting for places using your command in code, you can much more easily find it, and it's less brittle when refactoring or renaming a command.

Hope this helps,

Joel

P.S. Have you seen how we work with Laravel teams? We do not charge by the hour.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.