khanvuthy's avatar

Model const

Dear all, I seen some code look like this :

Model


const DRAFT = 'DRAFT';
    const APPROVED = 'APPROVED';
    const PERMANENT = 'PERMANENT';
    const TEMPORARY = 'TEMPORARY';
    const FULL_TIME = 'FULL_TIME';
    const PART_TIME = 'PART_TIME';

Controller


$query = Job::where('status','=',Job::APPROVED)

I am not understand how it's work. Anybody explain me please.

0 likes
5 replies
topvillas's avatar

It's so you don't have to use "magic" strings.

$query = Job::where('status','=',Job::APPROVED)

Is better and easier to maintain than

$query = Job::where('status','=','APPROVED')

3 likes
ChristophHarms's avatar

Imagine that in the future you decide that the "approved"-status should not be represented by the string "APPROVED", but you want to switch to numerics (draft=0, approved=1, and so on). Using constants, you would only have to change it in exactly one place instead of having to remember and/or hunt down all the places where you check the status.

Now imagine you're not working on a project alone, but with 50 or 100 people, so you didn't even write all the codepieces that check this status. Would be very frustrating having to locate all the places and then changing the string there. That's why it's good practice to use constants. Whenever you have a string in your code, it's worth stopping and thinking about if you really need a plain string there. Same goes for numbers. These are (as @topvillas stated) called "magic" strings and numbers, and in most companies, your code won't pass QA with them.

For further reading, check this Wikipedia article on magic numbers

1 like
tatenda's avatar

thanks alot just learn something important today

Please or to participate in this conversation.