I have a couple of controllers on my site which are handling form data. The forms use AJAX and I have quite a few methods across different controllers which are having to do some specific processing to return errors in a JSON encoded format - see code below. Obviously this isn't DRY and I need to move this code into a single helper function which I can use globally, but I'm wondering where this should actually go! Should I create a static helper class which contains this function (e.g Validation::build_ajax_errors()), or as this code is producing a format which is application specific and tied into the jQuery validation plugin I'm using, should it be a static method stored in, for example, my main Website controller which the form handling controllers extend from?
//if ajax request, output errors
if (request::is_ajax())
{
//need to build errors into array form for javascript validation - move this into a helper method accessible globally
$errors = $post->errors('form_data/form_error_messages');
$i = 0;
$new_errors = array();
foreach ($errors as $key => $value)
{
$new_errors[$i][0] = '#' . $key;
$new_errors[$i][1] = $value;
$new_errors[$i][2] = "error";
$i++;
}
echo '{"jsonValidateReturn":' . json_enco开发者_StackOverflowde($new_errors) . '}';
return;
}
IMHO, your question boils down to a question of personal programming style. When I've identified a piece of code that needs to be refactored in order to conform to the DRY principal, I don't always refactor it in the same way.
If I understand correctly, you need this function/method in your form classes, and all of those form classes extend the same base form class. In that case, I would promote the method in question into the superclass (I know that you mentioned that you wanted the method to be available "globally," but the rest of your use case seemed to imply that the function/method would only be used in your form classes.).
When I actually have a helper function that I need available throughout the application (and I'm for sure that there's nowhere else to put it), I place it in the application's entry point. Using the Zend Framework's MVC, that entry point would be the public index.php (all requests are routed through index.php, making it the logical place for global functions). At the bottom of that file I always add some helper functions to save myself some typing while debugging. See "The most useful function you will ever use . . ." as an example.
精彩评论