標籤:des blog http java 使用 strong
進入後Web年代之後,MVC架構進入了快速演化的時代,Struts等垂垂老矣的老一代MVC架構因為開發效率低下而逐漸被拋棄,新一代的MVC則高舉敏捷的大旗,逐漸佔領市場,其中的代表有Rails (ruby), .NET MVC (.NET), Django (Python),Symfony (PHP)等等,這些架構的思想都大同小異,這裡列舉出Rails3和.NET MVC的一些的區別,以方便Web開發人員從Rails遷移到.NET MVC,或者反之,從.NET MVC遷移到Rails.
產生項目
Rails和.NET MVC都能夠產生項目的基本骨架,只是產生的方式略有不同,Rails採用的是命令列的方式:
Java代碼
- rails tapir
而Microsoft則秉承其強大的IDE,提供了項目嚮導。
最終得到的目錄結構,僅在測試和配置項上略有不同。
| Rails |
ASP.NET MVC |
| /app/models |
/Models |
| /app/controllers |
/Controllers |
| /app/views |
/Views |
| /public/javascript |
/Scripts |
| /public |
/Content |
| /db |
/App_Data |
| /test |
單獨的VS項目 |
| /config |
/Global.asax, /Properties, Web.config |
值得一提的是rails的一個亮點:rails可以預先配置三個不同的環境:開發、測試、最終產品,可以通過RAILS_ENV這個環境變數來做簡單切換,.NET MVC並未提供這樣的配置環境,你可以通過手工配置來完成。
模型Model
Rails預設採用ActiveRecord作為模型,當然切換到其他的架構也很簡單,可選項有 Neo4J, MongoDB,和DataMapper。在Rails中,還是採用命令列來建立模型,Rails會產生一些骨架代碼,包括:模型、遷移任務和測試。你可以用-o來選擇其他模型、-t來選擇其他測試架構:
Java代碼
- $ rails g model customer name:string email:string
- invoke active_record
- create db/migrate/20100419094010_create_customers.rb
- create app/models/customer.rb
- invoke test_unit
- create test/unit/customer_test.rb
- create test/fixtures/customers.yml
Rails預設採用Sqlite3作為後台資料庫,而且Rails會很貼心的為開發、測試、生產三個環境分別產生一個資料庫拷貝。
在Rails中,所有的資料庫的操作都通過指令碼和遷移來完成,Rails中的遷移應該是最有價值的一個東西,當不同的開發人員同時在修改一個資料庫,或者您在升級現有的生產環境下的資料庫,遷移就顯示出它的強大威力:
Java代碼
- class CreateCustomers < ActiveRecord::Migration
-
- # Called when migrating up to this version
- def self.up
- create_table :customers do |t|
- t.string :name
- t.string :email
- t.timestamps
- end
- end
-
- # Called when migrating down from this version
- def self.down
- drop_table :customers
- end
- end
我們可以通過rake db:migrate命令遷移到不同的資料庫版本上去。
和Rails不同的是,.NET MVC並為綁定一個模型架構,你要從既有的架構中選擇一個適合你的,這個名單裡可以用Nhibernate,Linq to SQL, Entity Framework,Castle ActiveRecord或者Ruby的ActiveRecord,不過.NET MVC沒有遷移的概念,這有點遺憾。
大部分情況下Linq To SQL就很適合項目開發。
查詢語言
Rails3使用AREL(Active Record Relations),LINQ-to-SQL則使用LINQ。 二者都是相當優美的語言
Java代碼
- # A simple query with AREL
- User.where(users[:name].eq(‘Anders‘)).order(‘users.id DESC‘).limit(20)
Java代碼
- // The same with C#
- // Lambda Syntax
- db.Users.where(u => u.Name == "Anders").orderBy(u => u.Id).Take(20)
-
- // LINQ Syntax
- (from u in db.Users
- where u.Name == "Anders"
- orderby u.Id descending
- select u).Take(20);
現在除了在.NET中採用Ruby的ActiveRecord(藉助ironruby),目前還沒有其他架構提供類似Ruby的findbyXXX的功能,不過C# 4.0的method_missing使得這類架構應該會很快出現(比如Nhibernate 3.0)
控制器
在.NET MVC中,你在Controller目錄上點添加,就有很貼心的嚮導引導你為項目添加控制器,甚至還可以增加基本的CRUD的功能。
Java代碼
- public class CustomersController : Controller {
- // GET: /Customers/
- public ActionResult Index() {
- return View();
- }
-
- // GET: /Customers/Details/5
- public ActionResult Details(int id) {
- return View();
- }
-
- // GET: /Customers/Create
- public ActionResult Create() {
- return View();
- }
-
- // POST: /Customers/Create
- [HttpPost]
- public ActionResult Create(FormCollection collection) {
- try {
- // TODO: Add insert logic here
- return RedirectToAction("Index");
- } catch {
- return View();
- }
- }
- }
和Rails的腳手架代碼一樣,這些最基本的代碼99%會被廢棄,但是提供了“讓程式跑起來看看”的基礎。
Rails還是通過命令列來為項目增加控制器,你還可以在命令列裡制定為控制器產生哪些Action。
過濾器
Rails很容易為某個Action添加個過濾器
Java代碼
- class ItemsController < ApplicationController
- before_filter :require_user_admin, :only => [ :destroy, :update ]
- before_filter :require_user, :only => [ :new, :create]
- end
.NET也不含糊,只要重載OnActionExecuting就可以實現同樣的功能:
Java代碼
- override void OnActionExecuting(ActionExecutingContext filterContext)
- {
- var action = filterContext.ActionDescriptor.ActionName;
- if (new List<string>{"Delete", "Edit"}.Contains(action)) {
- RequireUserAdmin();
- }
- if ("Create".Equals(action)) {
- RequireUserAdmin();
- }
- }
或者通過.NET的attribute更漂亮的完成
Java代碼
- [RequireUserAdmin("Delete", "Edit")]
- [RequireUser("Create")]
- public class CustomersController : Controller
路由
在Rails中,可以修改routes.rb來修改路由,預設的Rails的路由被配置成RESTful:
Java代碼
- Tapir::Application.routes.draw do |map|
- resources :animals
-
- get "customer/index"
- get "customer/create"
-
- match "/:year(/:month(/:day))" => "info#about",
- :constraints => { :year => /\d{4}/,
- :month => /\d{2}/,
- :day => /\d{2}/ }
- match "/secret" => "info#about",
- :constraints => { :user_agent => /Firefox/ }
- end
通過rake routes你可以快速查看路由的結果。
ASP.NET MVC的路由稍微複雜一些,不過同樣強大:
Java代碼
- // Global.asax.cs
- public class MvcApplication : System.Web.HttpApplication {
- public static void RegisterRoutes(RouteCollection routes) {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- // Constrained route
- routes.MapRoute( "Product", "Product/{productId}",
- new {controller="Product", action="Details"},
- new {productId = @"\d+" } ); // Constraint
-
- // Route with custom constraint, defined below
- routes.MapRoute( "Admin", "Admin/{action}",
- new {controller="Admin"},
- new {isLocal=new LocalhostConstraint()} );
- }
- ...
- }
-
- public class LocalhostConstraint : IRouteConstraint {
- public bool Match ( HttpContextBase httpContext, Route route,
- string parameterName, RouteValueDictionary values,
- RouteDirection routeDirection )
- {
- return httpContext.Request.IsLocal;
- }
- }
View
二者在View上的表現十分接近,添加控制器的時候,會自動建立相應的視圖,規則也類似:視圖所在的檔案夾以控制器的名字命名,視圖的檔案名稱則以控制器的action命令,二者也都提供了從某個模型建立腳手架視圖的能力。
Partials
Rails和Asp.NET MVC都提供了在檔案中包含部分HTML檔案能力,ASP.NET MVC的檔案採用ASP,而Rails預設是ERB或HAML.
Java代碼
- <!-- Rails -->
- <%= render ‘form‘ %>
Java代碼
- <!-- ASP.NET MVC -->
- <% Html.RenderPartial("Form", Model);%>
.NET MVC 2中更做出了一些改進,提倡用2個替代的方法來產生代碼:
Java代碼
- <%= DisplayFor("Address", m => m.Address ) %>
-
- <%= EditorFor("Address", m => m.Address ) %>
尾聲
這篇文章對Rails和.NET MVC作了一個快速的瀏覽,目的是讓有相應編程經驗的程式員能快速瞭解另一個架構。無論Rails還是.NET MVC,都只是一個工具,一個好的程式員應該能隨心擺弄他的工具,而不是被工具所擺布。
參考:
http://blog.jayway.com/2010/04/23/asp-net-mvc-vs-rails3/