A magic number is a configuration parameter typed as a number in the middle of some code.
And that magic number is a bad thing.
Using this library, you will fix the following code:
To such:
How to use this generator?
First of all, install composer package:
composer require dobron/laravel-db-enum-generator
Let's say the user_roles database table has the following structure:
Id | Slug | Role |
---|---|---|
1 | MANAGER | Admin |
2 | CONTENT_CREATOR | Editor |
3 | MODERATOR | Moderator |
4 | ADVERTISER | Advertiser |
5 | INSIGHTS_ANALYST | Analyst |
Now call artisan command make:enum
.
# with laravel model
php artisan make:enum UserRoleTypes --model=UserRole --id=Id --slug=Slug --title=Role
# with laravel model that does not have slug column (will be auto-generated from --title)
php artisan make:enum UserRoleTypes --model=UserRole --id=Id --title=Role
# with database table
php artisan make:enum UserRoleTypes --table=user_roles --id=Id --slug=Slug --title=Role
# etc.
The UserRoleTypes.php
file was generated in the ./app/enums/
directory.
If you update the database table, just use the same command with the --force flag to overwrite the file.
How to find magic numbers in the project?
I recommend using a library called PHPMND.
This stands for PHP Magic Number Detector.
A detailed installation guide can be found at https://github.com/povils/phpmnd
But if you're using Composer, here's how you can install it quickly:
composer require --dev povils/phpmnd
Once that's done, you run it like this:
phpmnd .
Top comments (0)