The seldom used hook_requirements()
Whilst writing the Video Upload module, I came across Drupal's hook_requirements() function. As it turns out, this is the perfect place to check for all the little stuff your module requires in order to function properly.
For example, the video upload module won't work at all unless it has a YouTube developer key, a username and a password configured. As such, the Drupal admin will get a warning everytime they browse to the admin page if these 3 requirements aren't met:
<pre> if ($phase == 'runtime') { $username = variable_get('video_upload_youtube_username', false); $password = variable_get('video_upload_youtube_password', false); $developer_key = variable_get('video_upload_youtube_developer_key', false); // must have certain settings to use if (!$username) { $requirements['video_upload_username'] = array( 'title' => $t('Video Upload: Username'), 'value' => $t('Not Found'), 'severity' => REQUIREMENT_ERROR, 'description' => $t('The Video Upload module requires at least one YouTube username/password combo, which can be set <a href="!url">here</a>.', array('!url' => url('admin/settings/video_upload'))), ); } if (!$password) { $requirements['video_upload_password'] = array( 'title' => $t('Video Upload: Password'), 'value' => $t('Not Found'), 'severity' => REQUIREMENT_ERROR, 'description' => $t('The Video Upload module requires at least one YouTube username/password combo, which can be set <a href="!url">here</a>.', array('!url' => url('admin/settings/video_upload'))), ); } if (!$developer_key) { $requirements['video_upload_developer_key'] = array( 'title' => $t('Video Upload: YouTube Developer Key'), 'value' => $t('Not Found'), 'severity' => REQUIREMENT_ERROR, 'description' => $t('The Video Upload module requires a <a href="!devurl">YouTube Developer Key</a>, which can be set <a href="!url">here</a>.', array('!url' => url('admin/settings/video_upload'), '!devurl' => url('http://code.google.com/apis/youtube/dashboard'))), ); } </pre>
If these 3 requirements are there, the module attempts a YouTube connection:
<pre>
if ($username && $password && $developer_key && !_video_upload_authenticate_youtube()) {
// failed to connect/authenticate
$requirements['video_upload_authentication'] = array(
'title' => $t('Video Upload: YouTube Authentication'),
'value' => $t('Failed'),
'severity' => REQUIREMENT_ERROR,
'description' => $t('The Video Upload module has the required information, but was
unable to authenticate to YouTube. There may be an error in one or more of the following: !list
These settings can be reviewed <a href="!url">here</a>.', array('!list' => theme('item_list',
array('username', 'password', 'developer key')), '!url' => url('admin/settings/video_upload'))),
);
}
</pre>The hook_requirements(), while not as thorough creating detailed unit tests, is quite good at telling a non-technical user what might be going wrong with any given module installation.
Comments
Post new comment