In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this article, the editor introduces in detail "how to achieve the multi-tier architecture of MVC". The content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to achieve the multi-tier architecture of MVC" can help you solve your doubts.
What is a multi-tier architecture?
Multi-tier architecture is a strategy that developers adopt to deal with complex and changeable requirements in the development process. With regard to the standard of multi-tier architecture, I think there is a more representative saying that "each layer can be deployed separately." the most traditional and simplest is to start with three layers:
The whole project is divided into data persistence (data access) layer, logic (business) layer and UI (presentation) layer from bottom to top.
Data access layer: the data storage device responsible for persisting the data response, such as DataBase,Txt,Excel, etc.
Business logic layer: responsible for handling a series of logic and services customized to meet software requirements. For example, after a user places an order at the front end, the whole business flow may involve obtaining user information, obtaining commodity information, obtaining shopping cart information, verifying whether the purchasable quantity of goods meets this purchase, generating different preferential policies for user identity, and verifying the validity of data generated by Cookie,Session and other terminals. Finally, the order will be generated, and after the order will be generated, it will involve a series of Erp system business, such as warehousing and logistics, all of which belong to the business logic of "placing an order".
Presentation layer: the interface responsible for interacting with users, where a good user experience is mostly used.
If you have studied Petshop, you are no stranger to the three layers:
But with the complexity of the business, each layer will have its own evolution, and finally there are countless frameworks and development ideas attached to the three layers.
Mvc and MVP:
First of all, I have always thought that these two things belong to the presentation layer, "presentation layer MCV" and "presentation layer MVP".
Then we think about "Mvc" and "MVP" from the perspective of the presentation layer.
Mvc: divided into model,Controller,View, I believe everyone is already familiar with him, so I won't repeat it here.
MVP:MVP has three levels of Model-Presenter-View.
In fact, when the landlord first came into contact with Mvc, he was thinking whether it would be "unclean" to interact with Model directly through Controller, because in the eyes of the landlord, the "Controller of the presentation layer" should do the most for different responses and calls to the request routing, but many examples will verify some data and put the bad operation process in the Controller. When MVP appears, everything satisfies the landlord's fantasy, the process of P is to meet this demand, P plays the role of intermediary, responsible for receiving view requests, and then mapping the results to view, P can not make strong references to View, but adapt multiple view through IView. Of course, I will also do some verification and filtering for terminal data here.
Business logic:
It is clear from the description that the most complex and out-of-control layer of the whole top-down structure is the business logic layer, because it contains many uncontrollable factors, and the requirements of each industry domain may contain its own domain knowledge. So in the subsequent development of multi-tier architecture, more changes and wisdom are reflected here.
Domain driver: limited to my knowledge can not share too much here, in case of misleading, want to know more can refer to other Daniel in the garden, in fact, there is no 3, 5 years of relevant experience is difficult to understand, personal feeling if you do not understand, it will not have any impact on you, because domain driver is based on good face object analysis and boundary demarcation. In the process of learning, it has helped you to learn enough knowledge, and it doesn't matter if you don't get to the top of the mountain.
To put it simply, the most important thing about this idea is to diverge with the business domain as the core, hoping that other parts of the change program will not affect the domain model. That is, in order to "the behavior of business rules in complex system applications (that is," domain logic ") will often change, we have to embrace this change. Structure diagram:
CQRS: refers to the separation of command query responsibilities, is a small pattern, the key to this pattern is: "A method is either used to change the state of an object, or to return a result, the two will not co-exist at the same time." Split the entire system into two parts:
Commands (command)-changes the state of an object or entire system (sometimes called modifiers or mutators).
Queries (query)-returns a value without changing the state of the object.
Architecture diagram:
Whether DDD or CQRS, neither of them is 100% suitable for all project architectures, which requires architects to choose according to the characteristics and requirements of the project, but the ideas can be applied anywhere in the project.
Message-based distribution:
In fact, no matter what kind of architecture is used and what kind of architecture idea (soa) is added, what the core or developer wants to achieve most is hierarchy, decoupling between systems, and complex things that no one will like.
With the development of the system, our program will involve multiple servers and a variety of terminals, and we have introduced a message-based distributed architecture for decoupling.
First of all, the communication of the system is based on the message, the logical connection will not involve the specific business implementation, and the message transmission is more cheap and adaptable to a variety of terminals.
Second, since the logic used is only based on message implementation, the cost of iteration is faster and more convenient than other coupling projects.
Display layer:
With the arrival of Web2.0, the information displayed on a single page is also more abundant, and the popularity of Ajax,js also makes the operation of the UI side more and more heavy, so we expect to embrace this change with an engineering idea, so the Mvc framework of MVVM,js appears one after another. At the same time, with the rise of the mobile Internet, different terminals are also very important for system docking, so we consider introducing Application or Service layer between Ui and Logic to deal with different terminal configurations.
For example, we added WCF to Client Presenter Layer to adapt to orders submitted by a variety of terminals, all based on messages. The landlord's previous e-commerce system was aimed at orders from Taobao, Tmall, and Amazon. In order to avoid the concurrency of orders in the library, resulting in "overbought", we adopted the solution of introducing OrderChannel layer between the upper Ui and logic layers to queue different terminal orders.
The above is the process of building an architecture that can adapt to different needs, but the real truth needs to be learned from practice and mistakes.
The following is the simple small layered structure of the landlord, inappropriate, inadequacies I hope you guide the axe to correct.
Hierarchical division:
In order to achieve separate deployment, the layers are decoupled, so the layers are implemented based on interfaces.
The DataAccess layer introduces warehousing to achieve unified DTO operation, which is based on Ef:
IRepository:
Public interface IRepository where T:class {IEnumerable FindAll (Expression exp); void Add (T entity); void Delete (T entity); void Submit ();}
Introduce RepositoryBase implementation interface definition:
Public class RepositoryBase:IRepository where T:class {DbContext context; public RepositoryBase (DbContext _ context) {context = _ context;} public RepositoryBase () {this.context = new TestDBEntities ();} public IEnumerable FindAll (Expression exp) {return context.Set () .Where (exp) } public void Add (T entity) {context.Set () .Add (entity);} public void Delete (T entity) {context.Set () .Remove (entity);} public void Submit () {context.SaveChanges ();}}
For a single warehouse, we separately introduce its own warehousing interface:
Public interface IUserRepository:IRepository {IList GetAllById (int id); bool CheckUserExist (UserTest u);}
Specific warehousing implementation:
Public class UserRepository: RepositoryBase,IUserRepository {public IList GetAllById (int id) {using (TestDBEntities entities=new TestDBEntities ()) {var users = from u in entities.UserTests where u.ID = = id select u; return users.ToList () }} public bool CheckUserExist (UserTest u) {using (TestDBEntities entities = new TestDBEntities ()) {List users = entities.UserTests.Where (ut = > ut.UserName = = u.UserName & & ut.UserPassword==u.UserPassword). ToList (); return users.Count==0? False: true;}
Also set up relevant interfaces to adapt to special services in the Service layer:
IUserCore:
Public interface IUserCore {CommandStatueEnum UserLogin (IModel model); CommandStatueEnum UserRegister (IModel model); List GetUsers (Expression expr);}
UserCore:
Public class UserCore: IUserCore {# region Structure IUserRepository _ repository; public UserCore (IUserRepository repository) {this._repository = repository;} # endregion public CommandStatueEnum UserLogin (IModel model) {try {UserLogin u = model as UserLogin; UserTest uTest = new UserTest () UTest.UserName = u.Username; uTest.UserPassword = u.Password; if (_ repository.CheckUserExist (uTest)) {return CommandStatueEnum.Succeed;} else {return CommandStatueEnum.Fail }} catch (Exception ex) {throw ex;}} public CommandStatueEnum UserRegister (IModel model) {try {UserLogin u = model as UserLogin UserTest uTest = new UserTest () {UserName=u.UserName, UserPassword=u.Password}; _ repository.Add (uTest); _ repository.Submit (); return CommandStatueEnum.Succeed;} catch (Exception ex) {throw ex } public List GetUsers (System.Linq.Expressions.Expression expr=null) {return _ repository.FindAll (expr). ToList ();}}
Controller:
Public class AccountController: Controller {IUserCore userCore; public AccountController (IUserCore _ userCore) {this.userCore = _ userCore;} / GET: / Account/ # region view public ActionResult Home () {ViewBag.Users = userCore.GetUsers (u = > u.IsUse==1); return View () } public ActionResult Login () {return View ();} public ActionResult Register () {return View () } # endregion # region Post [HttpPost] public ActionResult Login (UserLogin account) {try {if (userCore.UserLogin (account) = = CommandStatueEnum.Succeed) {return RedirectToAction ("Home") } else {return View ();}} catch (Exception ex) {ExceptionModel.IsExcept = true; ExceptionModel.Exception = ex.ToString () ExceptionModel.CreateTime = DateTime.Now; return View () }} [HttpPost] public ActionResult Register (UserLogin account) {try {if (userCore.UserRegister (account) = = CommandStatueEnum.Succeed) {return RedirectToAction ("Home") } else {return View ();}} catch (Exception ex) {ExceptionModel.IsExcept = true; ExceptionModel.Exception = ex.ToString () ExceptionModel.CreateTime = DateTime.Now; return View ();}} # endregion}
We decouple the interfaces by introducing the IOC tool:
Public class MvcApplication: System.Web.HttpApplication {protected void Application_Start () {AreaRegistration.RegisterAllAreas (); WebApiConfig.Register (GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters (GlobalFilters.Filters); RouteConfig.RegisterRoutes (RouteTable.Routes); BundleConfig.RegisterBundles (BundleTable.Bundles); AuthConfig.RegisterAuth () # region IOC var builder = new ContainerBuilder (); SetupResolveRules (builder); builder.RegisterControllers (Assembly.GetExecutingAssembly ()); var container = builder.Build (); DependencyResolver.SetResolver (new AutofacDependencyResolver (container)) # endregion} private void SetupResolveRules (ContainerBuilder builder) {/ / Components are wired to services using the As () methods on ContainerBuilder builder.RegisterType () .As (); builder.RegisterType () .As () }} after reading this, the article "how to implement the Multi-tier Architecture of MVC" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.