One Good Reason to Use Constants in PHP/Laravel

preview_player
Показать описание
Quick tip on why it's convenient to use constants instead of just some numbers.

- - - - -

- - - - -
Рекомендации по теме
Комментарии
Автор

I don't use them... until now! This definitely is a good use case. Thanks Povilas!

adammenczykowski
Автор

The reason why Carbon constant didn't appear in your search is because "Directory" was selected as root directory for "Find in path" window. Selecting the "In Project" instead would've solved the issue :)


One note would be to always add visibility to your constants (they are public by default). To me, making it more explicit is a way to go.

Lgotdtaf
Автор

what about putting these logical constants used globally in system centrally in a config file ? we can use that any where and can change just from one place.

randomguy
Автор

Your examples are very good. Don't mind the prodigies opinions.

andreicozma
Автор

In this particular case i guess its better to separate the alert into another blade file and include it wherever you need it. Then you just change it in one place. Also for this particular problem, it would be better to have the day that defines the start of the week in a system wide configuration or per user configuration. Otherwise, you made a pretty good point regarding code readability.

AngelGabrielVargasBeltran
Автор

Even though I see your point, I'd say these two are bad examples for someone who just started development in general and came here, not just in PHP/Laravel.


Putting the ROLE_ADMIN, or ::MONDAY would work just fine, but as you said, someone who's new gotta dig the code just to find that little piece of the puzzle. You know that you should not ever map something relative to the code directly, just because it will fail at some point. Wouldn't be easier just to save ::MONDAY or ADMIN_ROLE to the table and instead off using constants make something like:


Edit: Or of course if you are fan of instead of settings()

or ->whereHas('roles') .. where role.name/title is SUPER_ADMIN. That way even when role changes, nothing will screw up.

Cheers!

beganovich
Автор

OMG, remember Ctrl + Shift + F and learn how to navigate in your project. It's easy to find that existing notification, then select it, Ctrl + Shift + R and refactor it everywhere in the project. :) However using the constant is better in your example, but that's just one single case. Please, next time make better example and do not step on libraries. Now prove to me why I should use constants in PHP/Laravel? Where to declare them, how to use them etc. I think this tutorial is somehow more confusing then helpful.

KrasimirTodorov
visit shbcf.ru