In MVC, if I have utility classes, will they be part of the models?

6

For example, let's assume that I have a string manipulation class called strman that I will use to store operations to work with strings, already in the models folder I have usuario and usuarioDAO , in case of class% how can it get along with the classes I have in the models?

And if it's even a model and can stay in this folder, how can I organize it so that it does not mix with the logic of the application? (I say the main logic that are the classes that contains the rules of the business, not utilities as string manipulators)     

asked by anonymous 06.01.2016 / 11:17

2 answers

3

If these are really utilities, you should organize under a structure of that category, usually a directory / namespace called Helpers , Utils , Services , depends on which nomenclature your environment or framework uses.

They should not be part of your model because your operations are more generic and mainly because they are not directly linked to the flow of operations of your business rules. As you said yourself, they're just utilities.

A practical example:
A certain application when registering a blog post must generate a slug for this record. Although you could generate this slug in the very function or method that persists in registering to the database, it would be far better if you extracted this operation to a more appropriate application category, such as service or helper , or even stringutils . Now you can use this slug generator not only on the method where blog post persistence occurs but also anywhere you need to create a slug from a string.

    
06.01.2016 / 11:48
3

It's not cool these classes of utilities.

In your case, create a folder called Extensions and then create a StringExtensions class and put all methods within it to handle strings.

Example, if you put a method to count words:

public static class StringExtensions
{
    public static int WordCount(this String string)
    {
        return string.Split(new char[] { ' ', '.', '?' }, 
                         StringSplitOptions.RemoveEmptyEntries).Length;
    }
}   

And then to consume:

var nome = "Renan Cavalieri";
var totalPalavras = nome.WordCount();
    
06.01.2016 / 11:43