I have a class that takes care of all network request. So my confusion is where should i call this network request class either from viewcontroller or model class. Suppose i have 'User' model class with properties id,name,phone. In order to access login API, should i create a function 'loginwithphone' within this model class and call it from viewcontroller or should i call network request class directly from Viewcontroller. Is the network request class considered as a model in itself? If so, calling it from viewcontroller will still make my code architecture as MVC. Doesnt it?
You should take a look to Observer pattern which defines MVC architecture, to define any way to manage your request through callbacks.
Model layer of MVC architecture defines your POJOS, so 'loginwithphone' function should be in a controller class, for example 'logincontroller'.
To sum up, your network request class should be considered as a class inside a resources layer. and should call your controller class.
Hope it helps!
In MVC you should call the network request through a networking class. Preferably you will first run a class or enum that will build the request for you. After that you will get the model object returned to you that you will have stored in your viewController and send to all the views you want to populate.
Off-topic: I like MVVM as you then call another class (viewModel) which holds all the models and the requests, and all you have in your viewController are views and callbacks waiting for the viewModel to finish it's requests.
Example:
//ViewController
self.viewModel.fetchData()
self.viewModel.dataFetched = {
view.populate(withData: self.viewModel.datas)
}
//ViewModel
var dataFetched: (() -> ())?
var datas: [Data] = []
func fetchData() {
let request = networkManager.buildRequest()
sendRequest( success: { datas in
self.datas = datas
dataFetched?()
})
}
This is a very vague description of how its done. But i like this way
Related
Working sample available at: https://gitlab.com/nipunrd_git/mvvmarch
I am in process of migrating an app from MVC to MVVM. As far as I have read, you need to make your viewController independent of the Model, there by making a viewModel to glue the model and the controller together.
If we consider a simple screenA which has a refresh button to get some data via a web service and then fill the data in the view:
ScreenAViewController.swift: Will contain the code to hit the web service via a singleton network helper class.
ScreenA -> NetworkHandler -> fetchData
In order to make ScreenA, use the fetched data, we should now make a ViewModel, so I made ScreenAViewModel. Let's say our model was named "Design":
struct Design{
var pattern: String
}
Now our ViewModel would look like this:
class ScreenAViewModel{
private let design: Design
public let pattern: String
init (design: Design, pattern: String){
self.design = design
self.pattern = design.pattern
}
}
When we get the data from the web service, we should first create a Design model and then initialize our ViewModel with that. This ViewModel will now be used by our view controller to fetch and display data from. Any Business logic will be written in this only.
Is there a way to shift #3 to the view model itself? I think by having this conversion from model to viewModel in the controller itself is beating the purpose of hiding model from controller.
Let's say I have a Car object with standard attributes like color, model, brand, and number of seats.
Each view controller in my app would be responsible for getting each of those attributes until the end:
Color View Controller --> Model View Controller --> Brand View Controller --> Seats Controller --> Result Controller
The way I pass data between each controller right now is through a Singleton, but I've read online that is is an anti-pattern and creates a lot of coupling later. Question is then: what is the best way for me to funnel all of the data to Result Controller?
Try to modify your singletons to services.
For example: your singleton StateManager has two method: set(state: SomeState) and getState() -> State.
First, use protocols:
protocol StateManager: class {
func set(state: SomeState)
func getStatus() -> SomeState
}
Second, your app modules shouldn't know about witch StateManager they use:
class MyAppController: UIViewController {
var stateManager: StateManager?
...
}
And when you init your VC:
let vc = MyAppController()
vc.stateManager = ConcreteStateManager.sharedInstance
//present vc
If you have a centralized place for create VC, you can hold instance of ConcreteStateManager in it, without calling sharedInstance.
Also, read about Dependency injection in swift.
This question might sound dumb, but I am new to asp.net mvc and can't find the answer to my question.
In my application ( a game) I have a model of the game GameModel (it contains a multidimensional array). What I want is to be able to use the same object in every controller I use. So I create it once and after that use it in every controller function.
Basically there is one view, and all other functions in the controller edit the object with functions of the model.
My idea was put the object in a session variable, make a function to check the session variable if the object is not set set the object. But this does not look logic to me, hopefully someone has a better solution.
According to your question, you want to keep track of a user's data (game data).
Storing GameModel in Session variable make sense for that scenario.
If you see yourself calling that Session variable from a lot of places, you can create a BaseController and keep it there. Then inherit all controllers from it.
For example,
public class BaseController : Controller
{
public GameModel CurrentGameModel
{
get
{
var model = Session["GameModel"] as GameModel;
if (model == null)
{
model = new GameModel();
Session["GameModel"] = model;
}
return model;
}
set { Session["GameModel"] = value; }
}
}
public class HomeController : BaseController
{
}
Note: You have to keep in mind that if Application Pool recycles or Application crashes, all data stored in Session variable will be lost.
If you want to persist data, you need to store in persistent storage like database.
I don't understand why you don't think Session looks good. It's purpose is exactly keeping data per user througout multiple requests.
You could also return the state of the game to the client using hidden fields. That would be even better than Session, given that your game state doesn't change in the server, as a response to someone else's action.
And finally you can use a static property of a class. Static properties in ASP.NET are kept alive througout the application lifecicle and are visible equally to all users. Meaning, if a user writes something there, another user can read it. You can allocate data per user using a Dictionary<>, though, where the key is the user Id.
Here is the scenario, I need to load up a view model object from a several domain objects that are being returned from multiple web service service calls. The code that transforms the domain model objects into the digestible view model object is a bit of fairly complex code. The three places that I have thought about putting it are:
Internal methods inside of the controller to load up an instance view model.
Static get method or property on the view model class itself that returns a loaded instance of view model.
An altogether separate builder or helper class that has a Static get method, property, or overloaded constructor that returns the loaded instance of view model.
To be clear, I don't want to use AutoMapper, or tools like it. From a best practices standpoint I'd like to know where this logic should go, and why.
EDIT
So here is what I have so far, this does give me "skinny" controller logic and separation of concerns. How can I make it better though?
// ** Controller **
public ActionResult Default()
{
var viewModel = MyViewModelBuilder.BuildViewModel(MarketType.Spot);
return View(SpotViewUrl, viewModel);
}
// ** Builder **
// Lives in MVC project under ViewModelBuilders folder
public class MyViewModelBuilder
{
public static ChartsModel BuildViewModel(MarketType rateMarket)
{
var result = new ChartsModel
{
RateMarket = rateMarket,
DateRange = new DateRange()
};
LoadGroupedRateLists(result, rateMarket);
LoadCoorespondingRates(result);
return result;
}
private static void LoadGroupedRateLists(ChartsModel model, RateMarket rateMarket)
{
var rateHistSvc = new RateHistoryService(RatesPrincipal.Current.Session.Token);
var serviceResult = (rateMarket == RateMarket.Spot)
? rateHistSvc.GetSpotNationalRateHistory()
: rateHistSvc.GetContractNationalRateHistory();
// Break lists apart by category, and re-sort and trim.
model.Cat1Rates = CategorizeTrimAndSort("cat1", false, serviceResult);
model.Cat2Rates = CategorizeTrimAndSort("cat2", true, serviceResult);
model.Cat3Rates = CategorizeTrimAndSort("cat3", false, serviceResult);
model.Cat4Rates = CategorizeTrimAndSort("cat4", true, serviceResult);
model.Cat5Rates = CategorizeTrimAndSort("cat5", false, serviceResult);
model.Cat6Rates = CategorizeTrimAndSort("cat6", true, serviceResult);
// Get Date range from results.
var sortedRateMonths = serviceResultNational
.Select(rate => rate.YearMonth)
.OrderBy(ym => ym.Year)
.ThenBy(ym => ym.Month);
model.DateRange.Start = sortedRateMonths.First();
model.DateRange.End = sortedRateMonths.Last();
}
...
}
1 or 3, not 2. Provided that if you do #3, you do not actually let the static method do the web service calls, just let it do the mapping. Domain object(s) in, viewmodel(s) out. Prefer extension method to overloaded constructor, if the object doesn't need to track state, there's no benefit to making it non-static.
Why?
As soon as you put a logic method on the model, it ceases to be a POCO. Best practice is to treat viewmodels like boring data buckets as much as possible. Some people also try to do the mapping in a viewmodel constructor which is not a good idea once you get into any kind of complexity in the mapping.
If you only need to do the mapping in one controller, you can put it in a sub-routine. Keep in mind if you want to test the sub in isolation and keep it internal, your project will have to have InternalsVisibleTo your test project.
Update
After looking at your code, I am kind of inclined to agree with #C Sharper that this belongs neither in the controller, viewmodel, nor helper class / method. Composing this ChartsModel is very interesting code, and contains a lot of business logic. It really should be in a separate layer. Your controller should call down into that layer and delegate all of this interesting and important code to another abstraction. That abstraction should then return a domain object, as #C Sharper said. Whether you use that domain object as your viewmodel, or DTO it into a different viewmodel, is up to you. Here's how something like that might look like:
public class MyController : Controller
{
private readonly IComposeChartData _chartDataComposer;
public MyController(IComposeChartData chartDataComposer)
{
_chartDataComposer = chartDataComposer;
}
public ActionResult Default()
{
var chartComposition = new ChartCompositionSettings
{
MarketType = MarketType.Spot,
Token = RatesPrincipal.Current.Session.Token,
};
var chartData = _chartDataComposer.ComposeChartData(chartComposition);
var chartModel = Mapper.Map<ChartsModel>(chartData);
return View(SpotViewUrl, chartModel);
}
}
That is a nice lean controller body. The abstraction might then look something like this:
public class ChartDataComposer : IComposeChartData
{
public ChartData ComposeChartData(ChartCompositionSettings settings)
{
// all of the interesting code goes here
}
}
This way, your viewmodel does not need to move out into a separate layer, but you do need to create a similar object (ChartData) in that layer. The interface decouples your controller from the data it needs, and the object it returns is cohesive with your presentation data (viewmodel).
I guess I don't really see this code as business logic, but more as
presentation logic. Why do you see it as business logic?
Think of your RateHistoryService class as a supplier. You receive raw materials from it, and transform those raw materials into something different, creating value in the process. This is what businesses do.
In this case, the chart visualizations are the value you are providing. Otherwise, your customers would have to sift through the raw data, trim it, categorize it, sort it, group it, etc., themselves before they could create similar charts.
I probably should have explained this earlier, but the service calls
are to our own business layer already, and return domain layer
business objects. It seems weird to me to have more than one business
layer.
Your business layer can have its own internal layering. In this case, you can create a RateChartingService that uses the RateHistoryService to return a RateChartingResult busines object. Then map that to a ChartsModel (or like I said before, use it directly as your viewmodel).
I would say don't do it in your Controller. Controllers should be as "skinny" as possible. I would do it like this.
Your "Data Layer" would assign the Domain objects its properties and values.
Then your subsequent Layer call it "Business Layer" will transfer your Domain Object into your ViewModel. And you will simply pass the view model to your controller without having the Controller handle any of that logic.
Separation is very important. Domain Objects should stay out of the controller, and the controllers should only care about View Models.
In the MVC model, where does the responsibility of loading the view model lie?
Should the Controller load the data?
Should the View Model itself load the data ala:
MyViewModel viewModel = MyViewModel.Create(someValue);
Should a Service Layer load it ala:
MyViewModel viewModel = MembershipService.Instance.Load(someValue);
See this example of the really clean technique:
http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/29/how-we-do-mvc-view-models.aspx
Alternatively you can do it manually: see "ASP.NET MVC In Action" book or CodeCampServer sources for examples. Basically you inject IViewModelMapper { public ViewModel Map(data); } to the controller. The neat thing is that it makes your IoC automatically pass services and repositories to your ViewModel mapper. However this can really make controllers be bloated with mapper interfaces so something like Jimmy Bogard's technique, even without AutoMapper, but with action filters than do pick IViewModelMapper, would be better.
If you can't do this, then I'd suggest stick with ViewModel handling mapping as Mathias suggested.
UPDATE: here's an example of automapper-like configuration with bits of CodeCampServer way. Not sure if it will work as is (or useful at all), just a demonstration.
public abstract class ViewModelMapper<Source, ViewModel> where Source: class, ViewModel: IViewModel
{
public abstract ViewModel Map(Source source);
}
public class ProductDetailsViewModel
{
public ProductViewModel Product { get; set; }
punlic IList<Language> AvailableProductLanguages { get; set; }
}
public class ProductDetailsViewMapper: ViewModelMapper<Product, ProductDetailsViewModel>
{
private ILanguageRepository languages;
public ProductDetailsViewMapper(ILanguageRepository languages)
{
this.languages = languages;
}
public override ProductDetailsViewModel Map(Product source)
{
var vm = new ProductDetailsViewModel();
AutoMapper.Map<Product, ProductDetailsViewModel>(product, vm);
vm.AvailableProductLanguages = languages.GetAppropriateFor(product);
}
}
public class ViewModelMapperActionFilter: ActionFilter
{
Type mapperType;
public ViewModelMapperActionFilter()
{
}
public ViewModelMapperActionFilter(Type mapperType)
{
}
public void OnActionExecuted(ControllerContext context)
{
var model = context.Result.ViewData.Model;
var mapperType = this.MapperType ?? this.GetMapperTypeFromContext(context);
// this is where magic happens - IoC grabs all required dependencies
var mapper = ServiceLocator.GetInstance(mapperType);
var method = mapperType.GetMethod("Map");
Check.Assert(method.GetArguments()[0].ArgumentType == model.GetType());
context.Result.ViewData.Model = method.Invoke(mapper, new[]{model});
}
}
public class ProductsController: Controller
{
[ViewModelMapper(typeof(ProductDetailsViewMapper))]
// alternatively [ViewModelMapper()] will auto-pick mapper name by controller/action
public ActionResult Details(EntityViewModel<Product> product)
{
// EntityViewModel is a special type, see
// http://stackoverflow.com/questions/1453641/my-custom-asp-net-mvc-entity-binding-is-it-a-good-solution
return View(product.Instance);
}
}
//Global.asax.cs:
IoC.Register(AllTypes.DerivedFrom(typeof(ViewModelMapper<>)));
The controller is the glue that binds the model and view together. You want both your model classes and views to have as few dependencies as possible on the other layers of your app. Therefore, the controller should always load data for the view, regardless of where the data comes from, or what design patterns you use in your model for retrieving it.
You may have a bunch of layers of abstraction for your data loading operations within your model layer, but the controller should be calling some method, or methods, which at some point down the call chain, goes to whatever persistent datastore you are using and gets the data needed for your view.
The controller should be providing all of the objects that the view needs, as this is really one of its key responsibilities. Whether that means using the appropriate model object to grab the data from a database, or initializing a "view model" class to wrap all the objects and properties needed for the view to display, it doesn't matter.
Personally, I have always used Linq-to-SQL in conjunction with ASP.Net MVC, and have had great success using repository classes that grab the necessary objects from the data context. To allow my controllers to be unit tested, I use a dependency injection framework (StructureMap in my case) to have ASP.Net MVC provide my controller with a default instance of my repository interface.
the controller should never load data. that should be in either the model or in a data layer.
my preference is in a data layer so i can seperate it from the model which i think isa there only to store/represent data that is given to the controller and then the view.
i implement the repository pattern for data retrieval
I like to have the ViewModel load the data.
ViewModels are accessible from all Controllers. That way its possible to avoid code dupplication.
See this sample ASP.NET MVC - Job of Controllers
I layer things this way:
view->controller->service->persistence
Requests flow from front to back; responses go from back to front.
The persistence layer worries about the database; it makes model data available. It knows nothing about any of the other layers.
The service layer's methods map to use cases. It knows about the persistence layer, units of work and transactions. It validates its inputs, acquires database connections, makes them available to the persistence layer, cleans up resources, and works with model objects to fulfill the use cases. It can be exposed as a web service or EJB if needed.
The controller and view go together. It knows about the service layer. It maps requests to services, binds and validates incoming request parameters, passes them to the service layer, and routes responses to the appropriate view.
The view only worries about displaying the data that the controller provides for it. It knows about the controller.
So it's the service that deals with the database. Controller and view collaborate to display info, nothing more.