PHP example of using class constants for well defined and easily maintained options.
<?php
class MusicSearch {
// -----------------------------------------------------------------------------------------------------------------
// CONSTANTS
// -----------------------------------------------------------------------------------------------------------------
// categories options
const CATEGORY_ALBUM = 1;
const CATEGORY_SONG = 2;
// search fields options
const SEARCH_FIELD_ARTIST = 1;
const SEARCH_FIELD_TITLE = 2;
// -----------------------------------------------------------------------------------------------------------------
// PROPERTIES
// -----------------------------------------------------------------------------------------------------------------
private $tables = Array(
self::CATEGORY_ALBUM => 'album',
self::CATEGORY_SONG => 'song',
);
private $fields = Array(
self::SEARCH_FIELD_ARTIST => 'artist',
self::SEARCH_FIELD_TITLE => 'title',
);
// -----------------------------------------------------------------------------------------------------------------
// METHODS
// -----------------------------------------------------------------------------------------------------------------
public function search ($category, $field, $term) {
// obviously normally you use escaping strategy like binding
$searchSql = 'SELECT * FROM `'.$this->tables[$category].'` WHERE `'.$this->fields[$field].'` = "'.$term.'"';
return $searchSql;
}
}
// ---------------------------------------------------------------------------------------------------------------------
// EXAPLE USAGE
// ---------------------------------------------------------------------------------------------------------------------
$ms = new MusicSearch();
// Hopefully find Michael Jackson's Thriller album
echo 'Example #1: '.$ms->search(MusicSearch::CATEGORY_ALBUM, MusicSearch::SEARCH_FIELD_TITLE, 'Thriller')."\n\r";
// Hopefully find Soulja Boy's Crank That song
echo 'Example #2: '.$ms->search(MusicSearch::CATEGORY_SONG, MusicSearch::SEARCH_FIELD_TITLE, 'Crank That')."\n\r";
// Hopefully find Paul Simon's albums
echo 'Example #3: '.$ms->search(MusicSearch::CATEGORY_ALBUM, MusicSearch::SEARCH_FIELD_ARTIST, 'Paul Simon')."\n\r";
// Hopefully find Swollen Members' songs
echo 'Example #4: '.$ms->search(MusicSearch::CATEGORY_SONG, MusicSearch::SEARCH_FIELD_ARTIST, 'Swollen Members')."\n\r";
~ » php -f MusicSearch.php
Example #1: SELECT * FROM `album` WHERE `title` = "Thriller"
Example #2: SELECT * FROM `song` WHERE `title` = "Crank That"
Example #3: SELECT * FROM `album` WHERE `artist` = "Paul Simon"
Example #4: SELECT * FROM `song` WHERE `artist` = "Swollen Members"