Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place reusable code accessible for controllers and models

I have some functionality related to currency conversions in my Zend project. I'd like to make use of the functionality in Controllers as well as Models. Is there a best practice for where to put this code? Or is the fact that the functionality's used in both places an indicator that perhaps I should rethink the structure of the project so it's not needed in both places?

like image 479
user1140535 Avatar asked Jan 10 '12 10:01

user1140535


1 Answers

I think the purists would argue that if you're doing currency conversions in your controller code then you're probably doing something wrong, as there shouldn't really be any business logic in there. However, sometimes practical considerations outweigh purist concerns. Let's assume that this is one such case. :-)

If your currency class is a fairly simple utility-type class, then I'd lean towards creating a new directory under "application" called "utils" and then adding that directory to the resource loader in the application bootstrap:

protected function _initResourceLoader()
{
    $this->_resourceLoader->addResourceType( 'utility', 'utils', 'Utility' );
}

Then you can create a class called Application_Utility_Currency stored in the file named Currency.php in that directory and call static methods such as:

Application_Utilility_Currency::convert( $from_currency, $to_currency, $amount );

This approach would be especially useful if you had other utility classes that were also looking for a home.

However, if your currency class contains richer functionality (such as connecting to external services to obtain exchange rate data, etc), then it would, IMO, be better to treat it as a "Service" rather than a "Utility". My definition of "model" is fairly loose and includes all data-related services, whether that data is located in the application database or elsewhere, so if the class is of the more complex variety, then I would just stick it in with the other models.

like image 157
JamesG Avatar answered Oct 23 '22 05:10

JamesG