Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I keep my constants in PHP [closed]

Tags:

php

enums

Right now I am having a big amount of constant strings and enums in my project. Since the beginning of it I was using the following approach (pseudo php example code):

class Constants implements iStatuses, iEmailTypes {
}

interface iStatuses {
    const STATUS_NEW = 1;
    cosnt STATUS_UPDATED =2;
    ...
}

interface iEmailTypes {
    const EMAIL_TYPE_NEW = 1;
    const EMAIL_TYPE_UPDATED =2;
    ...
}

This approach allowed me to get my constants in a following way anywhere in a code, since I included 'Constants' class in the index.php.

$this->sendEmailByType(CONSTANTS::EMAIL_TYPE_NEW);

However, I can totally see downsides of the approach:

  1. Constants class is overloaded with a lots of enums and constants and it is very hard to get right constant. Naming convention helps to solve it, but I don't like this, since it requires additional thinking to identify what constant I need
  2. Constants class is too big and messy
  3. I need to keep tracking of all the interfaces, being implemented by Cosntants class.

Since my project is becoming much more bigger now, and we need to merge it with another project's code, it is required to have class Constants approach changed. However, I got too many dependencies based on that class. How should I re-struct that approach, in order not to break old code that used values of constants class.

Please, share your thoughts and suggestions, how to improve my 'constants' approach, or confirm that it is decently good and I should support it.

Thank you in advance.

like image 804
Alexander Capone Avatar asked Apr 04 '16 08:04

Alexander Capone


Video Answer


1 Answers

Why not just having constant classes for each context. i.e.

class Statuses 
{
    const STATUS_NEW = 1;
    const STATUS_UPDATED =2;
    ...
}

class EmailTypes 
{
    const EMAIL_TYPE_NEW = 1;
    const EMAIL_TYPE_UPDATED =2;
    ...
}

Later on when you or other programmers want to contribute to your application they easily can check related constants on the subject they expecting, instead looking into a large pool of constant.

.e.g once looking for a flag around email types I would expect to find it within EmailType:: and if its not there, feel confident to add it in the same class.

like image 196
Ali Avatar answered Sep 28 '22 03:09

Ali