I have two particular cases where I disagree with a coworker, whether constants should be used or not.
We use a homemade framework working roughly like Symfony 1.x.
Initial code was, in a routing PHP config file for routing, like this one:
$router->map('/some_url', array('module' => 'some_module', 'action' => 'some_action')); $router->map('/some_other_url', array('module' => 'some_module', 'action' => 'some_action')); // etc.
The coworker changed it to:
$router->map('/some_url', array(MODULE => 'some_module', ACTION => 'some_action')); $router->map('/some_other_url', array(MODULE => 'some_module', ACTION => 'some_action')); // + in constants.php file: define('MODULE', 'module'); define('ACTION', 'action');
IMO this is constant overuse: if the concept of "module" or "action" is ever renamed, it would have to be renamed in the entire code, either written as a string or a constant. Plus, the defined constant names above have no specific meaning, favoring naming collisions/confusions.
Initial code example:
if (isset($_SESSION['unid']) && isset($_SESSION['login'])) { ... }
Modified by the coworker:
if (isset($_SESSION[UNID]) && isset($_SESSION[LOGIN])) { ... } // + in a constants.php file: define('UNID', 'unid'); define('LOGIN', 'login');
In our application, those session vars names
unid
andlogin
are clearly unlikely to change. Nonetheless, if declaring constants was really a good practice here, I would suggest at least more precise names, for exampleFIELDNAME_UNID
andFIELDNAME_LOGIN
...
Is introducing those constants really relevant (that is, naming should just be improved), or (as I guess) completely useless ?
Thanks.
EDIT
After a few months, here are a few (incredible) lines from the constants.php file. I definitely find this a completely useless mess, similar to this DailyWTF post. Too many constants kills constants.
define('POST', 'POST');
define('GET', 'GET');
define('PROJECT', 'project');
define('APPLICATION', 'application');
define('MODULE', 'module');
define('ACTION', 'action');
define('ID', 'id');
define('SLUG', 'slug');
define('CONTROLLER', 'controller');
define('CONTENT', 'content');
define('AJAX', 'ajax');
define('EXECUTE', 'execute');
define('FORMAT', 'format');
define('BASE_HREF_CONSTANT', 'basehref');
define('UNID', 'unid');
define('USERNAME', 'username');
define('PASSWORD', 'password');
define('TEMPLATE', 'templates');
define('UNSECURE', 'unsecure');
define('MODE', 'mode');
define('MESSAGE', 'message');
define('TEMPORARY_SESSION', 'temporary_session');
define('ERRORMESSAGE', 'errormessage');
define('START_FROM', 'startfrom');
define('COUNT', 'count');
// and so on.