Should I use MVC both on client and server?

2019-03-21 06:08发布

问题:

I've decided to use MVC Pattern on my site. So, now I use Backbone.js framework on my site. All actions on my site are ajaxy, so server only gets data from db, and saves data to db.

Do I need to use MVC on the server side too? It's complicating all, isn't it?

Or I may use MVC on client side, and have simple server api, that only fetches/saves data and makes some small server job?

UPD: I understand that I should use Models on server side. But what are Views for on server side - if I render all information with javascript?

So, Is it a good pattern, that server side works only with raw data - models - it always returns json, and has no relation with html-markup and other things related to Views ?

回答1:

No, you don't need to use it server-side, but it will help with organization / separation of application and business logic. Depending on the scale of your application, that could help tremendously in the future.

The key is just making sure you organize your backend code well, otherwise you will end up with a monolithic and/or difficult-to-maintain codebase.

Edit in response to OP's edit:
Server-side views would contain your HTML and any JavaScript that may or may not make requests to the server. This assumes that you are actually using PHP to build the pages that a user navigates to.

If you have a static html page that builds itself using AJAX requests, then you may not need to use server-side views at all. Your controllers would more than likely be outputting JSON data. If this is the case, it doesn't make models and controllers any less useful.



回答2:

Backbone.js connects your application over a RESTful JSON interface. I honestly find that it works wonderfully in conjunction with the MVC framework. If you build a RESTful API, you can let you server manage CRUD updates quite easily. All your server side code will be responsible is saving and sending back JSON objects to Backbone.js. Then let most of your logic and magic happen within the Backbone.js framework.



回答3:

If you are using any of the major PHP frameworks (CakePHP, Code Igniter, Symfony, etc.) then you ARE using MVC already. If your server side logic is more complex than just a few really simple scripts than you probably should be using one of those frameworks listed, using MVC on the server and the client.

Many (most?) larger web apps being built today are moving towards using an MVC framework for both client-side and server-side application code. It's a fantastic pattern for separating concerns for many large applications, especially request/response server apps and event-driven browser apps.