what constants do you define?

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

what constants do you define?

Post by s.dot »

I've recently got into defining constants. And I'm talking about on a project scope. Some paths change when moving from a local server to a production server.

IE: C:\Apache2\htdocs\some_site\images, would later become /home/some_site/public_html/images

Thus making use of

Code: Select all

define('IMG_DIR', '/home/some_site/public_html/images/');
That way, in the coding I can simply do move_uploaded_file(IMG_DIR.$file_name), without having to worry about changing it later.

What constants do you make a habit of defining?

Database connections?

Anything you NEVER define that most people do?
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

None.

Database details I especially avoid even remotely considering.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

Well what if the type of database to be used was dependant upon the user installing the application... like PHPBB.

ie

Code: Select all

<?php
define('DATABASE_TYPE', $_POST['database_type']);

//later on

require '../db/'.DATABASE_TYPE.'_db.class.php';
?>
That would make sense.

I'm trying to get a grasp of why things are defined, and when to use them. [This was meant to go in theory & design - apparently i can't read forum titles :lol: ]
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

I will usually define an include path, root path and a page include validator. Sometimes I define DB credentials. And a lot of times I will define numeric values so I can use them throughout as constants rather than trying to remember what the hell 424 does in my scripts.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

Constants I typically reserve for absolutely hardcoded values which are universal constants...

Code: Select all

define('PI', 3.14);
A path like you have shown is not a good constants to store in a constant, by virtue of the fact it's not really a constant it's variable as you suggest it is...

Likely best stored in a INI, XML, etc or some other storage medium suited for application settings.

Constants would be best used for things like application Version (major-minor) application name, etc.

Framework errors codes perhaps would be another example.

But paths, which as you say, might change are best stored in a medium which is easily edited like INI, XML, etc

of courswe if your writing a bare bones applications not dependent on other libraries, etc or just want a quick solution CONST works fine.

Cheers :)
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

I put all configuration data into an object. I don't think I ever use defines.
(#10850)
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

M_PI is pi

Constants are good but readonly variables are better. Not that readonly variables exist, I'm talking encapulation and data hiding here.
I used to use a lot of constants for project management:

Someting like this:

Code: Select all

if(isLocal) {
	define('databaseName',	'xxx');
	define('relativePath',	'xxx/xxx/xxx/');
	define('snapshotPath',	'c:/xxx/');
} else {
	define('databaseUser',	'xxx');
	define('databasePass',	'xxx');
	define('databaseName',	'xxx');
	define('relativePath',	'/');
	define('snapshotPath',	'/xxx/xxx/xxx/xxx');
}
define('absPath',		'http://'.$_SERVER['HTTP_HOST'].'/'.relativePath);
define('siteName',		'Some project');
define('contactAddress','xxx');
define('version',		'0.7');
//define('iconPath',		'placeholders/');
//define('iconPath',		'rva/');
define('iconPath',		'pw/');

define('contactAdminMsg',	'<br />Please contact the administrator '.administratorEmail);
define('stndQueryError',	'Error with query: '); // put mysql_error stuff afterwards
define('isLocal',			true);
define('stndDoctype',		'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
define('stndHTMLTag',		'<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">');

define('ADMIN_PASS','xxxxxx');

define('USER_ADMIN',1);
define('USER_GUEST',2);

// various truncations
define('RECENT_LIMIT',5);
define('RECENT_TRUNC_LEN',43);
define('LST_V_SIZE',60);
define('LST_R_SIZE',60);
define('LST_Q_SIZE',102);
define('LST_Q_STYLESHEET_SIZE',22);
define('ROWS_PER_PAGE',8);
define('MAX_ENTRIES',500);    
define('MAX_REPORTED_QUESTIONNAIRES',8);
define('MYSQL_TEXT_SIZE',65500);
define('MYSQL_VARCHAR_SIZE',255);
define('MAX_URL_SIZE',4096);
define('PRESET_NAME_LENGTH',200);
define('ANSWER_LENGTH',MYSQL_VARCHAR_SIZE);

define('TEXTAREA_WIDTH',45);

define('QTID_FREE_TEXT',1);
define('QTID_SMALL_CHOICE',2);
define('QTID_LARGE_CHOICE',3);

define('HEADER_HEADER',1);
define('HEADER_NAV',2);
define('HEADER_BODY',4);
define('HEADER_ALL',7);

// this will be used a couple of times as user-friendly message when null values are encountered
define('UNSPECIFIED_TEXT','<span class="strike">(unspecified)</span>');
*Shudder* those days are behind me now.

Actually a lot of constants like these I've replaced with the database. I store things like max length truncations and limiters and other values in a table so that should there be the need to make them modifible that won't really upset things. I use an object interface to that table to:
  • Prevent me from setting them without it being quite deliberate
  • Cache them throughout the application to minimize queries
  • Only query the ones I need
I'm not completely constant bashing here. A constant might not be as flexible or as clever as my database solution but is one hell of a lot better than a just using literals i.e. no constants or control system at all.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

M_PI is pi
Strictly used for the sake of example... :P
Constants are good but readonly variables are better. Not that readonly variables exist, I'm talking encapulation and data hiding here.
I used to use a lot of constants for project management:
edit: Just re-read your post, doesn't sound like you were saying quite what I thought you were saying :P so ignore the rest if you want ;)

Explain please? :?

Wrapping constants up inside a class, although technically allowed and arguably good/bad design, isn't exactly encapsulation, which you should know is a fancy word for data hiding and constants by definition are *not* data.

Data is dynamic and is calculated, thus an object manipulates it data. A constant is recurring and never changing and typically universal, such as PI or the speed of light, etc...

Wrapping a constant up in a class is being over zealous IMHO and poor use of OOP as a technology, but I suppose thats personal choice :P

I'm just saying that constants serve their purpose and scottay should consider all his options first before jumping on a band wagon.

Cheers :)
User avatar
daedalus__
DevNet Resident
Posts: 1925
Joined: Thu Feb 09, 2006 4:52 pm

Post by daedalus__ »

I never use constants.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

Daedalus- wrote:I never use constants.
:lol:

Before this turns into a gong show...I just wanna say, that is most PHP type applications, constants are not really common place. They typically have more use in framework, etc where values that don't change are somewhat universal truth's...

Application code, which PHP is usually used as, doesn't have constants in this regard, but rather application settings, so I can see where everyone is going when they say they never use constants.

Cheers :)
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

I use configuration objects *usually* but I do use the occassional constant for friendliness (additional flags for users to place on method calls).
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

Only time I use constants is if I'm making a function/method that has an option, as d11wtq says. Just so I keep in line with the likes of MYSQL_ASSOC etc.

For a read only data object..

Code: Select all

<?php

class Container
{
    private $_data;

    public function __construct(array $data = null)
    {
        if (is_null($data)) $this->_data = array();
        else $this->_data = $data;
    }

    public function __get($name)
    {
        if (!array_key_exists($name, $this->_data))
        throw new Exception('container::' . $name . ' not set.');
        else return $this->_data[$name];
    }

    // for instances where $name is invalid property name (such as numerical)
    public function get($name)
    {
        return $this->__get($name);
    }

    public function __set($name, $val)
    {
        throw new Exception('Container properties are read only');
    }
}

?>
Add your prefered method for adding data, wang it in the registry.. enjoy.
GM
Forum Contributor
Posts: 365
Joined: Wed Apr 26, 2006 4:19 am
Location: Italy

Post by GM »

I use constants typically to define custom status of objects - I don't typically delete many records from the database, I tend to change their status to "deleted", which would be some integer... For instance, in a Forum a thread might have status "Published", "Closed", "Deleted" etc., which in my database might be signalled by 0, 1 and 2.

So I'd define something like:

Code: Select all

define('THREAD_STATUS_OPEN', 0);
define('THREAD_STATUS_CLOSED', 1);
define('THREAD_STATUS_DELETED', 2);
So I could use

Code: Select all

if($thread->status == THREAD_STATUS_CLOSED) {
    //do stuff
}
Makes the code more readable and understandable.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Forgot to mention that I define table names.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

You know...this reminds me of that poll I started on application settings and config data...

Whether they are immutable or not...???

This is a classic example of perhaps why, I wasn't so "out there" myself...and perhaps reason to re-consider formalizing the two??? :P

Oh sure...Martin Fowler advocates the seperation of content from business logic using MVC, etc...which IMHO is just as trivial...but Hockey (That's me :P ) advocates the standardizing or at least defining volatile & immutable data to assist in making software development easier, by virtue of having to ask less questions during development...and everybody sneezes at the idea :P

Some group of forward thinkers you all are :P

Ha...relax...this thread is a joke...I mean...I'm personally serious, but don't expect any of you to take me seriously...I'm just picking at the skin underneath your toe nails :P

Cheers :)
Post Reply