I'm working on a new project and hoping to establish some magic methods in my classes to facilitate the getting/setting of private or protected values without forcing my devs to define a getter/setter for each and every property of each and every class. We're going to have to write a bunch of VO and DAO classes for our various database tables and writing and maintaining all those getters and setters would be a lot of work.
Based on this discussion, i'm hoping to use under_scores for $variable_names and camelCase for methodNames. Naturally, the need arises in this context to convert $some_variable_name automatically into setSomeVariableName and getSomeVariableName. Additionally we must convert them back form camelcase to underscores to get the name of the underlying property (i.e., to know that getSomeVariableName should retrieve the value of $some_variable_name).
I think I've got the basics covered fairly well with these two methods, but realize that their might be trouble with an underscore name such as some_x_var where there is a word with only one char and also with camelcase names with uppercase acronyms like someXVar.
toCamelCase routine turns "some_x_var" into "SomeXVar"
fromCamelCase routine turns "SomeXVar" into "some_xvar"
I think my functions should handle multi-letter acronyms pretty well, but the single-letter words present a problem.
If anyone could recommend a better algorithm, I would appreciate it. I'm also wondering if this is such a good idea. Perhaps there's a way to warn when there are ambiguous conversions?
/**
* A function to convert underscore-delimited varnames
* to CamelCase. NOTE: it does not leave the first
* word lowercase
* @param string str
* @return string
*/
public static function toCamelCase($str) {
$string_parts = preg_split('/_+/', $str);
if (!is_array($string_parts) || (sizeof($string_parts) < 1)){
throw new Exception("Unable to split the input string");
}
foreach($string_parts as $key => $string_part){
$string_parts[$key] = ucfirst(strtolower($string_part));
}
return implode('', $string_parts);
} // toCamelCase()
/**
* A function to convert camelCase varnames
* to underscore-delimited ones.
* @param string str
* @return string
*/
public static function fromCamelCase($str) {
$matches = NULL;
if (preg_match_all('/(^|[A-Z])+([a-z]|$)*/', $str, $matches)){
$words = $matches[0];
$words_clean = array();
foreach($words as $key => $word){
if (strlen($word) > 0)
$words_clean[] = strtolower($word);
}
return implode('_', $words_clean);
} else {
return strtolower($str);
}
} // fromCamelCase()