The only way to be sure you have a unique field name is to test on creation whether the same field already exists.
As you have realised, this is a problem when deploying your fields as a feature, as you do not know what environment your fields will be deployed in. Unfortunately Features does not provide you with a way to rename the fields when a feature is first enabled.
This is something you could implement yourself ; it should be possible to do this in a way that doesn't stop you from automatically re-creating the feature. Here is an idea about how this could be done:
(1) Name all your fields prefix_fieldname
(I will assume you used 'mymodpref' for the prefix) and ensure they are no more than (say) 30 characters ;
(2) In your module's .install file, implement hook_install
such that you find a safe field prefix that will make your fields unique. For instance:
function mymodule_install() {
$prefix = 'mymodpref';
$prefix_index = $prefix;
$index = 1;
$found_unique = FALSE:
while (!$found_unique) {
$c = db_query("
SELECT COUNT(*)
FROM {field_config}
WHERE field_name LIKE :prefix",
array(':prefix' => $prefix . '_%')
)->fetchField();
if ($c > 0) {
$prefix_index = $prefix . $index;
$index++;
} else {
$found_unique = TRUE;
}
}
if (strlen($index) > 2) {
// Our fields are up to 30 characters, so we can't have an index
// of more than 2 characters. If this happens we're in trouble -
// add some code here to tell the user we can't install the module.
} else {
variable_set('mymodule_field_prefix', $prefix_index);
}
}
(3) In you feature's main module file, add an implementation of hook_field_default_fields_alter
which allows you to change the default field definitions, and rename them with the right prefix :
function mymodule_field_default_fields_alter(&$fields) {
$prefix = variable_get('mymodule_field_prefix', 'mymodpref_');
$new_fields = array();
foreach ($fields as $key => $field_info) {
// Replace 'myentity' and 'mybundle' accordingly
if (strpos($key, 'myentity-mybundle-') === 0) {
$new_field_name = $prefix . '_' . $fied_info['field_config']['field_name'];
$field_info['field_config']['field_name'] = $new_field_name;
$field_info['field_instance']['field_name'] = $new_field_name;
unset($fields[$key]);
$new_fields['myentity-mybundle-' . $new_field_name] = $field_info;
}
}
$fields = array_merge($fields, $new_fields);
}