ASP.NET MVC to CakePHP questions - asp.net-mvc

I have been doing ASP.NET MVC at university this year and only touched on some of the basic principles but absolutely loved it. Having been a PHP fan for over 6 years I planned to use something like CakePHP to continue using the MVC pattern in my work.
However I have a few questions as their are MASSIVE differences between the two frameworks:
1.) How would someone do something similar to LINQ where when ever you do your actionresult you can simple build a query and then return it to the view?
2.) Do repositories exists in Cake? I love these in ASP.NET and the ability to create custom methods for your database logic and then call them anywhere.
3.) Confusion with the model. In ASP.NET I could have a single model deal with lots of tables and then call any table or combination of tables with ease. In Cake it seems you have a model per table???

CakePHP comes with its own persistence API, whereas in ASP.NET MVC you can (and have to) use something else of your choosing.
1) There isn't an equivalent to LINQ in CakePHP, but you can still construct queries pretty easily.
2) CakePHP's models can have functions attached, and they also have something called Behaviors which are neat.
3) CakePHP's persistence system associates one model with a persistent entity (such as a table). I'm not sure I can give a better answer with out a more specific example.
I did a lot of PHP work before I moved on to .NET. While I still like ASP.NET MVC or RoR better (mostly because they are better frameworks and languages, IMHO, than PHP), the few projects I did in CakePHP were very pleasant.

I am not familiar with ASP.NET, but I can answer some of these questions.
LINQ... I am not familiar with. If
you could give a simple example, I
could explain if there is a similar
method in Cake.
The Repositories you refer to can be
Behaviors as mentioned by
#HackedByChinese. However, you may
have better results by adding
functions to the app_model.php file.
All models in the app can access any
function in the app_model.php file
which can be added to your app
directory.
Yes. CakePHP is designed with code
separation in mind. The idea behind
a single table per model allows you
build a very FAT model and still
keep it manageable. You build all of
the relationships, validation, and
other model specific code into each
model. Then when something goes
wrong with Users for example, you
know you need to look in the Users
model. This can be overridden, you
can put all of the model access into
a single model file if you want, but
it makes the code sloppy. If you are
going to do that, why use Cake? Just
put all of your model code in
Model.php, all of your controller
code in Controller.php and all of
your view code in View.php and call
it good. I think you would agree
that is not the structure for very
readable nor extensible code.

Related

Where should I add a List All Users function when using MVC?

I'm aware that in model-view-controller, the Model is the class part.
If I have a User class and instantiate an object, the object must refer to a single user from the database.
So I'll have the CRUD methods on the user, for that specific user.
But if I need a function to run a SELECT * FROM Users, should I create a function within the User class? Or a function in a helper file? Or in the controller? Where should it go, in order to respect the MVC pattern?
I mean, it makes no sense to instantiate a User object just to run a function to display the Users table.
I'm not sure if this will raise "primarily opinion based" flags. I just don't know where those functions should go. If you guys consider the question worth closing, it's ok. But tell me in the comments in which stack community I should ask this.
Back up a bit. Let's go foundational for a moment.
In the MVC pattern
The model is your state (in simple terms), meaning a representation of the data important to the business functionality you are working with
The view is a way of presenting the state to the user (NOTE user here could be another system, as you can use MVC patterns for service endpoints)
The controller ensures the model gets to the view and back out of the view
In a system designed with good separation of state, business functions are not present in the model, the view or the controller. You segregate business functionality into its own class library. Why? You never know when the application will require a mobile (native, not web) implementation or a desktop implementation or maybe even become part of a windows service.
As for getting at data, proper separation of concerns states the data access is separate not only from the model, view and controller, but also from the business functionality. This is why DALs are created.
Before going on, let's go to your questions.
should I create a function within the User class? This is an "active record" pattern, which is largely deprecated today, as it closely couples behavior and state. I am sure there are still some instances where it applies, but I would not use it.
Or a function in a helper file? Better option, as you can separate it out. But I am not fond of "everything in a single project" approach, personally.
Or in the controller? Never, despite Scott Gu's first MVC examples where he put LINQ to SQL (another groan?) in the controller.
Where should it go, in order to respect the MVC pattern?
Here is my suggestion:
Create a DAL project to access the data. One possible pattern that works nicely here is the repository pattern. If you utilize the same data type for your keys in all/most tables, you can create a generic repository and then derive individual versions for specific data. Okay, so this one is really old, but looking over it, it still has the high level concepts (https://gregorybeamer.wordpress.com/2010/08/10/generics-on-the-data-access-layer)
Create a core project for the business logic, if needed. I do this every time, as it allows me to test the ideas on the DAL through unit tests. Yes, I can test directly in the MVC project (and do), but I like a clean separation as you rarely find 0% business rules in a solution.
Have the core pull the data from the DAL project and the MVC project use the core project. Nice flow. Easy to unit test. etc.
If you want this in a single project, then separate out the bits into different folders so you can make individual projects, if needed, in the future.
For the love of all things good and holy, don't use the repository pattern. #GregoryABeamer has a great answer in all respects, except recommending you create repository instances to access your entities. Your ORM (most likely Entity Framework) covers this, and completely replaces the concepts of repositories and unit of work.
Simply, if you need something from your database, hit your ORM directly in your controller. If you prefer, you can still add a level of abstraction to hide the use of the ORM itself, such that you could more easily switch out the data access with another ORM, Web Api, etc. Just don't do a traditional unit of work with tens or hundreds of repository instances. If you're interested, you can read a series of posts I wrote about that on my blog. I use the term "repository" with my approach, but mostly just to contrast with the typical "generic" repository approach you find scattered all over the interwebs.
I'd use some kind of 'Repository' layer. Then, my controller calls the UserRepository GetAll method and sends the data to View layer.

ASP.NET MVC Data Access Layer

I'm working on an ASP.NET MVC project. In my solution I have the following projects:
BlogApp.Web (ASP.NET MVC app),
BlogApp.Data (Class Library)
I'm wondering how to implement data access layer. I want to use EntityFramework Code First approach. I was thinking about Repository pattern, but is this really necessary? I have read that it is only the next layer on top of ORM, which isn't really needed. So instead of writing method like:
GetAllPosts(Tag t) {
db.Posts.Where(p => p.Tags.Contains(t)).Skip(x).Take(y).Select(p => p);
}
I create db context in controller and write the same query? I don't need to implement paging and write wrappers around my models.
What you may have heard about the Repository pattern is that it's falling out of favour in some camps - see for instance Jimmy Bogard's blog. This doesn't mean that queries should be written directly in controllers, unless your application is very, very simple.
As has been noted, your queries should be written in only one place which your controller can then use - this would either be in a Repository method or in a dedicated Query Object, both of which provide better abstraction and avoid duplication.
Regarding simplicitly - is your application intended to have multiple front-ends which will require a separate assembly for your data access layer? If not you might want to consider merging the two assemblies and just using namespaces to keep things organised.
Not sure whether this question belongs here.
Anyway, if you write data access logic in your controller, and the same logic is required in another controller, what would you do? Copy-Paste this into new controller? That's just not good. Anytime, you are copying and pasting you need to step back, there must be something wrong here (aka code smell).
Separating the logic into different layer will make your code more maintainable and testable. Trust me!

Is MVC Framework ill-equipped for rich page design?

Just to prefix this question, I've decided to take a look at moving our works old legacy systems (40+ programs from vb6, vba, vb.net to c#.net) into two separate systems using the same DAL (barcoding terminals and one web based system) as I spend most my day fixing crummy or non existant business logic in 15 year old vba programs. I've recently built an entity framework model complete with fluent validation and couldn't be happier with it after using it for a bit.
The small team is familiar with webforms (but not very) but the last few days I've explored MVC Razor. I was loving MVC Framework until I tried to start trying to add more functions onto the same page and then it seemed arbitrarily hard to replicate our a recent system I put in a webform. Before, I would eager load a customer and all it's child entities and then bind that to single page for the customer so they could access everything (which is what they wanted), it works okay and isn't slow. From this single page I could edit all their account details/contacts/emails/phones/jobs.
All the examples I've done and seen in MVC handle a single update, a single edit etc but surely you can't separate out every single action into a new view/page? I can pass a rich model through to the view in MVC, but then its a pain trying to update all the different child entities.
This is probably the exact design that MVC wasn't designed for maybe, which is okay, I'm willing to adapt it if MVC will be a better platform going forward, but how are you meant to handle adding this complexity in? Some methods I've seen:
Lots of partial views? passing child info to them (or the id and lazy loading it)?
I've seen methods that wrap multiple <forms> around everything and handle actions that way.
Separate pretty much every task out
If the solution is more lightweight and easier to maintain I'll go research whatever I need to I just wanted at an earlier stage to see if I'm wasting my time. Any pointers to the correct questions I should be asking would be greatly appreciated.
ASP.NET MVC is neither more or less better equipped to deal with complex pages than any other technology out there.
Certainly, MVC requires more low-level work than a Web Forms app, with no direct binding support, but in most cases this is a good thing and provides much more flexibility in how your page is rendered.
One of the whole ideas of MVC is to give you more control over things, but that control leads to requiring more knowledge and more effort on your part in most non-trivial cases. MVC provides a number of tooling functions to speed up trivial work (like creating standard table based CRUD) but when you have complex models, you will have to do much of the work yourself.
This is not that MVC is "ill suited" for it, but just that control and flexibility has a trade off with more responsibility on your part.
In your case, you simply create a view model with all the fields you want. Then, you create your form to edit those fields. In your controller, you will need to unflatten that view model and create or update the necessary records in the database. It's not difficult, but it's more work than WebForms databinding.
You could look into more advanced tools (commercial) for MVC, such as Telerik's tools, which have developed more of a databinding like interface, but MVC is not a drag-n-drop technology, and requires you to hook things up and write the various logic for what is done.
If you need drag-n-drop, databound functionality, then no.. MVC is not the correct technology. But then WebForms requires you to accept many compromises as well, and ties your hands in many ways.
You could use partial views, however I seldom use them. I prefer to instead use Editor/DisplayTemplates as these take care of naming your form fields correctly, even for collections and complex objects. PartialViews tend to have lots of gotchas if you aren't careful. I pretty much only use them as fancy includes, or when using Ajax.
I'm not sure what you meay by "wrap multiple <forms> around everything`. You cannot nest forms in HTML, it's not legal. If you mean place a form around each row of a table, that isn't valid html either in most cases (it's not legal to put a form in a between the table and the tr).
It would help if you had a specific problem that you could ask about, vague objections don't help us solve your issue.
You can accomplish anything in MVC that you can in WebForms. The difference is MVC will usually require you to write more code as it doesn't really offer you any "controls" to drop on your page.
In WebForms, it's easy to create a master/detail view with a GridView, FormView and then wrap everything in an UpdatePanel for automagical AJAX support.
In MVC, while you do have helpers like the WebGrid and AjaxHelpers extension methods, creating views and/or pages requires more understanding of how things work to get the desired functionality. When I start a new MVC project, here's what I include:
Backbone.js - client-side "ORM" that performs CRUD operations
against RESTful* APIs
Knockout.js - client-side view models and
real-time data-binding for your views
Knockback.js - wraps
Backbone models in Knockout view models
Using these three frameworks, you can quickly create powerful single-page apps using MVC and WebAPI.

Rails MVC concept in practice

I am not actually asking a question but rather an suggestion(or recommendation) on how to write code to fit nicely into Rails MVC pattern. Hope rails veteran or anyone familiar with MVC can give me some feedbacks.
I have an web app that talks to a RESTful api app via ActiveResource. It can fetch and update contents using API calls. It works perfectly. However, the web app does not have any models. The way it works is when user triggers an action(index,view,edit etc), the controller will directly call the REST api to fetch/update data.
My question is: Is it a good practice to do it this way or should I create models and populate data in there instead of directly calling the api? I was wondering if it is just a pragmatic compromise to MVC. I have just started working with Rails(and MVC) so I am open to any ideas, comments or recommendations on this
It's a bit of a catch-22 question. (I did wrote a huge answer but then deleted because it will be too tedious to read)
If you mean, can you implement the MVC pattern without a model, then the answer is no. The M means Model.
If they mean, can you use the MVC without using a model, then the answer is "yes", but it is no longer MVC, you have obliterated the the M i.e. Model.
I would recommend you to read MVC pattern in detail and then try to understand what your application actually trying to do.
http://c2.com/ is a very good place if you want to understand the design patterns.
A model is an object representing data or even activity, e.g. a
database table or even some plant-floor production-machine process.
A view is some form of visualization of the state of the model.
A controller offers facilities to change the state of the model.
Now in your case (it seems): you do have a data coming through via api so I would suggest populate the model properties and propagate it across.
Also Considering Pragmatic Compromise in MVC Dealing with things sensibly and realistically in a way that is based on practical rather than theoretical considerations. Omitting the use of Model in MVC do-not sound like a good idea, and it no longer remains MVC.
Having said that It seems from your point of view you are trying to say that Rails isn't necessarily strictly MVC hence why not use the way you want to :) but I will suggest to keep the integrity of MVC (and follow the purist approach).
http://c2.com/cgi/wiki?ModelViewController
Good read: jeff Atwoods: http://www.codinghorror.com/blog/2008/05/understanding-model-view-controller.html (Feel free to skip the asp.net part)
https://stackoverflow.com/questions/1242908/in-english-what-really-is-model-view-controller
sums it all :) source is mentioned above.
"The model consists of application data and business rules" (wikipedia)
A model is essentially a table in your database locally.
If you're not storing any data, not validating any data, then you don't need a model.
If you want to clean up your code, maybe put some functions in a helper or in /lib

ASP.NET MVC with Knockout and Web API: does it make sense?

does it make sense to use KnockoutJS Viewmodels in combination with ASP.NET MVC3 or 4? Because it is not very DRY, isn't it? I have to write models for EF, Viewmodels for the MVC Views and Viewmodels for Knockout... and i lose a lot of magic. Automatic client-side validations for example.
Does it make sense to use MVC at all if one sticks with the MVVM Pattern?
With Knockout Mapping, you can automatically generate a KO view model from your MVC view model.
This is a proper pattern: your models are raw entities, your data. Your views are the UI. And your view models are your models adapted to that specific view.
This may be an unpopular answer, but I don't use ko.mapping to translate my C# POCOs into JS viewmodels. Two reasons, really.
The first is a lack of control. ko.mapping will turn everything into an observable if you let it. This can result in a lot of overhead for fields that just don't need to be observable.
Second reason is about extensibility. Sure, ko.mapping may translate my C# POCOS into JS objects with observable properties. That's fine until the point you want a JS method, which at some point, you invariably will.
In a previous project, I was actually adding extra methods to ko.mapped objects programmatically. At that point, I questioned whether ko.mapping was really creating more problems than it solves.
I take on board your DRY concerns, but then, I have different domain-focused versions of my POCOs anyway. For example a MyProject.Users.User object served up by a UserController might be very different from a MyProject.Articles.User. The user in the Users namespace might contain a lot of stuff that is related to user administration. The User object in the Articles namespace might just be a simple lookup to indicate the author of an article. I don't see this approach as a violation of the DRY principle; rather a means of looking at the same concept in two different ways.
It's more upfront work, but it means I have problem-specific representations of User that do not pollute each others' implementations.
And so it is with Javascript view models. They are not C# POCOs. They're a specific take on a concept suited to a specific purpose; holding and operating on client side data. While ko.mapping will initially give you what seems to be a productivity boost, I think it is better to hand-craft specific view-models designed for the client.
btw, I use exactly the same MVC3/KnockoutJS strategy as yourself.
We use knockout Mapping to generate the KO view models well.
We have a business layer in a separate project that does CRUD, reporting, caching, and some extra "business logic". We aren't going to be using EF, or something similar. Currently we've defined c# classes as MVC models, and our controllers call the business layer to construct the Models that are defined in the usual place in our MVC app. These C# models get serialized as JSON for use in our pages.
Since everything we do in the browser is c#/JSON based using knockout, we aren't using MVC models in the traditional MVC way - everything gets posted as JSON and serialized to c#, so we don't use MVC model binding, validation, etc. We're considering moving these models to our business layer so they can be tested independently of the web app.
Se we'll be left with an MVC app that has controllers and views, but no models - controllers will get models that are defined in the business layer. We're nervous about departing from the normal MVC structure, but a KO/javascript based client is fundamentally different from a DOM based client that MVC was originally built around.
Does this sound like a viable way to go?
I work now on project which mixes MVC3 and knockouts and I have to tell you - it's a mess...
IMO it's nonsense to force some patterns just to be up to date with trend.
This is an old topic, but now in 2014 (unfortunately) I still feel this question has a huge relevance.
I'm currently working on a project which mixes MVC4 with knockoutjs. I had some difficoulties to find whichs part should be handled on which side. Also, we needed a "SPA-ish" kind of architecture, where each module has its own page, but then inside that module there is only AJAX interaction. Also faced some heavy validation scenarios, and needed to provide user (and SEO) friendly URLs inside each module. I ended up with the following concept, which seems to be working well:
Basic MVC and .NET side roles:
Handling authentication and other security stuff.
Implementing the Web API interface for the client-side calls (setting up viewmodels, retrieving and mapping data from the domain, etc.)
Generating knockout viewmodels from my (pre-existing) C# viewmodels with T4 templates, also including knockout validation plugin extensions from .NET validation attributes. (This was inspired by this aticle). The generated viewmodels are easily extensible, and the generation can be finetuned with several "data annotation"-like custom or built-in attributes (such as DefaultValue, Browsable, DataType, DisplayFormat, etc.). This way the DRY doesn't get violated (too much).
Providing strongly typed, but data-independent partial view templates for each submodule (each knockout viewmodel). Because property names on C# viewmodels are same as in KO models, I can benefit from the strongly typed helpers specifically written for KO bindings, etc.
Providing the main view for each module similarly to previous point.
Bundling and minification of all scripts and stylesheets.
Basic client-side roles:
Loading the initial state of all viewmodels encapsulated into one module page, taking the whole URL into account with a simple route parser implementation.
Handling history with history.js
Data-binding, user interaction handling.
Posting relevant parts of viewmodels to the server, and processing the returned data (usually updating some viewmodel with it).
I hope this could help anyone else who feels lost in the world of trendy technologies. Please, if anyone has any thought on this, feel free to post any question or suggestion in the comments.

Resources