Architecture more suitable for web apps than MVC? - php

I've been learning Zend and its MVC application structure for my new job, and found that working with it just bothered me for reasons I couldn't quite put my finger on. Then during the course of my studies I came across articles such as MVC: No Silver Bullet and this podcast on the topic of MVC and web applications. The guy in the podcast made a very good case against MVC as a web application architecture and nailed a lot of what was bugging me on the head.
However, the question remains, if MVC isn't really a good fit for web applications, what is?

It all depends on your coding style. Here's the secret: It is impossible to write classical MVC in PHP.
Any framework which claims you can is lying to you. The reality is that frameworks themselves cannot even implement MVC -- your code can. But that's not as good a marketing pitch, I guess.
To implement a classical MVC it would require for you to have persistent Models to begin with. Additionally, Model should inform View about the changes (observer pattern), which too is impossible in your vanilla PHP page (you can do something close to classical MVC, if you use sockets, but that's impractical for real website).
In web development you actually have 4 other MVC-inspired solutions:
Model2 MVC: View is requesting data from the Model and then deciding how to render it and which templates to use. Controller is responsible for changing the state of both View and Model.
MVVM: Controller is swapped out for a ViewModel, which is responsible for the translation between View's expectations and Models's logic. View requests data from controller, which translates the request so that Model can understand it.
Most often you would use this when you have no control over either views or the model layer.
MVP (what php frameworks call "MVC"): Presenter requests information from Model, collects it, modifies it, and passes it to the passive View.
To explore this pattern, I would recommend for you begin with this publication. It will explain it in detail.
HMVC (or PAC): differs from Model2 with ability of a controller to execute sub-controllers. Each with own triad of M, V and C. You gain modularity and maintainability, but pay with some hit in performance.
Anyway. The bottom line is: you haven't really used MVC.
But if you are sick of all the MVC-like structures, you can look into:
event driven architectures
n-Tier architecture
And then there is always the DCI paradigm, but it has some issues when applied to PHP (you cannot cast to a class in PHP .. not without ugly hacks).

From my experience, the benefits you get from an MVC architecture far outweighs its costs and apparent overhead when developing for the web.
For someone starting out with a complex MVC framework, it can be a little daunting to make the extra effort of separating the three layers, and getting a good feel as to what belongs where (some things are obvious, others can be quite border-line and tend to be good topics of discussion). I think this cost pays for itself in the long run, especially if you're expecting your application to grow or to be maintained over a reasonable period of time.
I've had situations where the cost of creating a new API to allow other clients to connect to an existing web application was extremely low, due to good separation of the layers: the business logic wasn't at all connected to the presentation, so it was cake.
In the current MVC framework eco-system I believe your mileage may vary greatly, since the principles are common, but there are alot of differences between, for instance, Zend, Django, RoR and SpringMVC.
If there are truly other good alternatives to this paradigm out there... I'm quite interested in the answers!
Sorry for the slight wall of text!

I think it would depend on what you're trying to do, personally. Magenta uses MVC pretty successfully, and it makes it fairly easy to add new functionality or modify existing.
Of course if you're trying to make something fairly simple, going with an MVC architecture could be overkill.

It's all preference. I have worked with old structures like XTemplates and Smarty and have now moved on to Codeigniter and Kohona. I like them very much and they work very well for everything I do on the web. For phone applications I can set up controllers for the functions that are needed to do it's data pulls as well. Working both in the Linux world and Windows World, for building ASP.NET Web Sites I don't see other way of building websites beside using MVC. Web Applications Projects in Visual Studio are still used but I prefer not to anymore. MVC Projects via Visual Studio is so easy to use and set up. You can right click on your controller methods and create views automatically. In every structure there is a good and bad but it's up to the developer to use whatever meets their needs.

Related

MVC style application architecture catering to API

I'm working on a "community" style website, both for fun and profit, and while the aesthetic element of it is coming along nicely, I haven't yet sunk my teeth into working out the application logic for reasons of unsureness in my approach.
I'm creating an PHP powered MVC style framework which I can hopefully reuse components of, however I've noticed that many existing MVC frameworks use a sort of "convention over configuration" to expedite the whole process. Some queries I intend to run are a little more complicated than SELECT * FROM entity_name.
I want to design the application in layers, so that API calls can be made to the server. I figured instead of doing everything twice, I would build my site controllers on top of this layer, so that everything follows a standard. This will allow Ajax calls, remote web application calls, etc., to follow the same route of request normalization and response as document web requests.
Anyways, perhaps much of that is unnecessary detail, but can anyone shed some light on API layered MVC architectures of this nature? Since the API level (the model layer) is where data is ultimately read/written, would I want to incorporate authentication at this level, or abstract it to a higher level and make that the entry point? What other considerations should I make that I haven't mentioned?
I know I still have much reading to do, so any suggestions for reading materials, or advice from personal experience with this is very welcome. Thanks in advance.
This is a very good question. I think my best bet would be to use an SOA approach with REST resources as much as possible If your website gets a lot of hits, it might be worth segregating state mutating from state exposing, so the first can use a more complex OO approach whilst the other can use simple DTOs (in the form of arrays) and retrieve the data from the database by using custom queries.

What is better: Developing a Web project in MVC or N -Tier Architecture?

I have asked a similar question before and got an convincing answer as well?
What is difference of developing a website in MVC and 3-Tier or N-tier architecture?
Due to the conclusion of this question I started developing projects in N-tier Architecture.
Just about an hour ago, I asked another question, about what is the best design pattern to create interface? There the most voted answer is suggesting me to use MVC architecture.
What is the best design pattern to design the interface of an WebPage?
Now I am confused, First post suggested me that both are similar, just a difference that in N-tier, the tier are physically and logically separated and one layer has access to the one above and below it but not all the layers.
I think ASP.net used 3 Tier architecture while developing applications or Web applications. Where as frameworks like Zend, Symphony they use MVC.
I just want to stick to a pattern that is best suitable for WebProject Development? May be this is a very silly confusion? But if someone could clear this confusion, that would be very greatful?
They aren't mutually exclusive. The Model-View-Controller pattern is really a user interface design pattern, and it concerns logical rather than physical tiers.
I most often hear "n-tier architecture" used to describe the actual physical separation of an application's layers. For example, a system in which the user interface runs in one process, exchanges data with an application layer (perhaps via messaging or web services) that executes in another process (perhaps on another server), which in turn accesses a data layer that runs in yet another process (typically a database server).
This description can be particularly confusing because 'application logic' can mean multiple things: in an n-tier system it usually means business logic - as opposed to user interface logic (like which widgets are enabled when the user selects a particular checkbox).
For example, in an n-tier system, your presentation layer might call a web service method that accepts an item ID. The web service runs on a different server, where it performs complicated calculations and returns a price.
In a simpler architecture, your application might calculate the item's price in the same process as the user interface - though the pricing logic may be separated into its own logical layer (perhaps within library or executable).
I can't think of any current MVC frameworks that care whether their layers run in separate physical processes or not.
I just want to stick to a pattern that
is best suitable for WebProject
Development? May be this is a very
silly confusion? But if someone could
clear this confusion, that would be
very greatful?
I think your confusion lies in two areas:
1) The assumption that there's one solution for every problem.
The requirement of your project will dictate which solution is best.
2) The definition of MVC when applied to the web is different than when it originally applied to desktop applications.
Some folks say that if the view doesn't talk to the model, then it can't be MVC. Well, most of the web MVC implementations don't have the view talk to the model, yet it's still called MVC.
Since you are a self-described amateur, you should embrace this one axiom early on: the programming world is confusing to everyone all the time.
You may want to review the Microsoft Application Architecture Guide. It has a good overview of the available Microsoft technologies from an Architecture standpoint. Chapters that might be of interest to you:
Chp 21 Designing Web Applications
Appendix B: Presentation Technology Matrix
Appendix C: Data Access Technology Matrix
As for what is best? You have to answer that yourself. Make some sample projects using MVC, WebForms, etc.
Web-based MVC is much different than the traditional desktop MVC. The Model simply has no way to update the View, because the web is (for the most part) stateless.
Even if you used AJAX to poll the server every couple seconds to check for Model updates, that still wouldn't be "true" MVC because it's not the Model notifying the View, it's the controller constantly "querying" the Models.
The lesson learned is that it really doesn't matter what you label your architecture. There are just so many variants of MVC/3 tier that usually people just lump them under the "MVC" blanket. And all of these are suitable for web development. I just can't think of any practical way to have the Model actually notify the View through server-side programming (at least not in PHP). If you need this kind of behavior, you should be writing a desktop application. Just write what is natural for you and don't get caught up in terminology debates. Look at what some of the well known frameworks like CodeIgniter, Kohana, Symfony, CakePHP, and Zend do and pick and choose which features or design patterns you like.
Why not use both?
At the moment I'm busy developing a project using the MVP pattern and in an N-tier architecture.
I'm using the MVP pattern in the user interface project, ie. the website. All the data which needs to be shown and used in the website is passed from a webservice. This webservice is connected to a business layer (BLL), which is connected to the data access layer (DAL). The DAL is connected to the database using the Entity Framework.
So in this project I'm using them both. Using MVP instead of MVC though.
This way the interface project (website) doesn't has to do hard stuff, only pass through some data which is received from the webservice. Took me a while to set up, but it works quite wonderfull.
Also, there is no real answer to which pattern or architecture is the best. It all depends on what you want and need. If you want to be scalable, an n-tier architecture is a good solution. If you want to be able to test your UI quite easily, an MVC pattern is good also. There's a ton of other patterns and architectures which would suffice as well, as long as you know how to use them.
There is no which is better. MVC and n-tier are not either or things. One is object/API design, one is system architecture. The question to distinguish between the two has been asked and answered here:
MVC Vs n-tier architecture

Why is the MVC paradigm best suited for web applications?

I'm fairly certain my professor will ask me why I chose to use MVC for my web application.
Truth be told, I'm new to MVC. I read about it, I'm building a blog application using it, I think it's very logical to approach a problem this way.
But why? O_O I draw a blank. How is better suited than say, building an N-tier application?
Well, basically: separation of concerns on the usage level, not the physical level.
Quoting PoEAA on MVC
MVC splits user interface interaction into three distinct roles.
With MVC , you are separating presentation (V, C) from the domain logic (M) and you also separate UI behavior (C) from UI display (V). This is much more maintainable than intermingling all three concerns into one and it also fosters reuse and testing. It allows you to better tackle complexity.
This is nothing that just applies to Web Applications. It is suitable for any applications with domain logic and a UI. With that said, I wouldn't say MVC is the best-suited pattern for a web app though. If all you wanna do is put, say, a Contact Form on the web, then an all-in-one-page script would be sufficient. If you only got a bunch of static pages, MVC is overkill too. So like with any patterns, it depends on the problem you want to solve.
As for the n-tier, the "classic" MVC did not foresee it's use on the Web. With the presentation of the UI happening in the browser and the controller on a remote server, MVC on the web is always also a Multi-Tier architecture, hence the difference between usecase and physical in the beginning. MVC is just not concerned where it happens.
Also see:
What is MVC and what are the advantages of it?
MVC VS N-Tiers

How is MVC more convenient?

I have a large website that I have time to convert to a nice custom-framework that I can build to my needs. I want to build my own, and not use something like Smarty because I'd like to...
know how all the guts of it work
cut any and all bloat
learn it, just for kicks
But, after building it in different ways, several times...I keep feeling that for the amount of "convenience" it offers, the code becomes increasingly unflexible, attempting to keep track of files becomes triple as hard (especially if you are the lone developer on the project), and there isn't even any real awesome documentation out there.
At this point, I really need convincing...how is this going to change my life, again?
This has been answered already, but to put a finer point on it, I think the single attribute that encompasses when to/not MVC is scalability:
MVC allows clear seperation of duties (ie, front-end vs. database coders).
MVC is a pattern that enforces uniform coding habits.
Maintainability is increased as it's easier for a new project member (who understands MVC) to grok the codebase.
If you are the sole owner of the code and don't forsee other people joining anytime soon, then you should not need it.
It can be difficult (sometimes impossible) To convert an existing project to some new pattern/framework. It also depends on how you are implementing an MVC framework.
You say that keeping track of files is hard. While you may end up with more files, they shouldn't be hard to keep track of if you have a good organization and naming system, i.e. keeping models, views, and controllers in 3 separate folders, or have some kind of naming convention that tells you what is what
I also don't understand why you see the code as more 'unflexible'. Having code properly seperated into Models, Views, and Controllers is that it is more modular, and it can prevent code duplication.
The most important thing about having this seperation of concerns is Maintenance. One of the biggest benefits of an MVC framework is that is easier to pick out what code is misbehaving and fix it. The seperation of concers = a seperation of problems & bugs.
It is probably most convenient in the sense that it is an accepted pattern, and other people drifting in and out of your project will understand it. The big thing about Design Patterns, the book, was not that the patterns were new, but that they all suddenly had accepted names.
If you are and will be the sole updater, it may be no big deal.
The greatest thing about MVC is that it's really just a concept. How you implement it is up to you as long as you follow the standard of separating duties.
I've written a few different MVC code bases based on what needs to happen in the project. One code base has a service layer to further separate "business logic" from the controller and views. Another one separated CLI controllers from web controllers.
This is just how I look at and use MVC. I suggest finding some credible documents or blog posts online about MVC.
What I love about MVC is that when you come to hand it over to another developer, whether that be a new employee or for long-term support, anyone with a knowledge of MVC can figure out what's going on very quickly.
That's not to say it's the best way of looking at things, but it is a way that most people understand.
After doing MVC or HMVC there is no way that I could possibly go back to spaghetti coding. It will take a bit of time to switch over a large site depending on how extensive the backend is, but depending on how much maintenance you are doing, it may be worth it.
Can i ask what makes you want to do a custom framework? I mean, I don't doubt anything, it is just that technology advancements keep growing-- I don't highly recommend drupal or cake.. I would recommend something like Kohanaphp.com where it is very lightweight and has a great database connector called ORM (object relational mapping) which is a great usage of MVC. The best part is that you won't have to fully maintain your framework as it is opensource and has an active community. Although, being a programmer myself, I do understand how we grow attached to our code and want it our way :D But this saves time by already offering tools for request handers, xss filtering, routing and bootstrap configurations, etc.
Just a thought :D

PHP: A Personal Framework

I'm going to write a framework for my web projects in PHP.
Please don't tell me about considering to use some existing framework (Cake, CodeIgniter, Symfony, etc.) - I have already had a look at them and decided to write one for myself.
The framework itself will mainly consist of a module system, a database handler and a template parser. (Many other things too, of course)
With module system I mean that every module has exactly one PHP file and one or more templates associated with it.
An example module would be modules/login.php that uses templates/login.tpl for its design.
These days everyone(?) is talking about the MVC (Model View Controller) concept and most of the existing frameworks use it, too.
So my questions are the following:
Is MVC really effective for a personal framework?
Would it be a bad idea to use a module system?
Did you ever write a framework for yourself? What are your experiences?
Is MVC really effective for a personal framework?
Yes, it can be. Although, it might be a little overkill (which, is not necessarily a bad thing if you are trying to learn)
Would it be a bad idea to use a module system?
This is never a bad idea.
Did you ever write a framework for yourself? What are your experiences?
I wrote a common security framework for my group's PHP applications when I was an intern. I learned alot, but the project as a whole might have benefited more from a pre-built solution.
Of course, I wouldn't have learned as much if I just installed a pre-built solution. So you always have to take that into account, especially for personal projects. Sometimes re-inventing the wheel is the only way you will learn something well.
Is MVC really effective for a personal framework?
What MVC means anymore, due to its vague interpretation, is business logic, presentation, and input handling. So, unless you aim to design an application that does not involve any three of those, MVC is, in its vague sense, very suitable.
Often it can be more formal than you desire, however, as it demands physical separation of ideas into different code files. Quick and dirty tasks or rapid prototyping might be more quickly setup if the formalities are avoided.
In the long term, what MVC asks for is beneficial to the sustainability of the application in ways of maintenance and modification or addition. You will not want to miss this. Not all frameworks encourage the right practices, though. I am not surprised that you find the various implementations you've tried insufficient. My personal favourite is Agavi. To me and others, in a world of PHP frameworks that do not feel right, Agavi emerges to do the right things. Agavi is worth the shot.
Would it be a bad idea to use a module system?
MVC asks you to separate components of business logic, presentation, and input handling, but it does not suggest how to layout the files. I presume this is the challenge you are addressing with a module system. To answer your question: modules serve identically to sub-directories. If the items are few, its probably more hassle to bother with subdirectories even if the files could logically be separated into them. When the number of items grow large, its now cumbersome to locate them all and sub-directories become a better option.
Frameworks will tack on functionality that allows you to deal with modules as their own configurable entity. The same functionality could just as well exist without modules, perhaps in a more cumbersome manor. Nonetheless, do not consider modules primarily as a system. Systems are so wonderfully vague that you can adapt them to whatever setup you find suitable.
Did you ever write a framework for yourself? What are your experiences?
Yes I have wrote several frameworks with various approaches to solving the issues of web applications. Every such framework I wrote became nothing but a vital learning curve. In each framework I made I discovered more and more the issues with building software. After failing to create anything interesting, I still gained because when asked to make a program I could fully do so with justice.
I recommend you continue if this is the sort of learning experience you want. Otherwise, give Agavi a shot. If that too fails, ensure that you have a clear and detailed specification of what your framework will do. The easiest way to barge into making software, work really hard, and accomplish nothing is to not decide before-hand what exactly your software will do. Every time I ran into making code the only thing in my mind was I will do it right. What happened was a different story: oh, well I need to make a routing system as that seems logical; hmm, okay, now I need a good templating system; alright, now time for the database abstraction; but gee, what a lot of thinking; I should look to the same system from software XXY for inspiration. Therein is the common cry that pleads to use existing software first.
The reason I thought I could do it right was not because all the nuts and bolts of the framework felt wrong. In fact, I knew nothing about how right or wrong they were because I never worked with them. What I did work with was the enamel, and it felt wonky. The quickest way to derive your own framework is really to steal the nuts and bolts from another and design your own enamel. That is what you see when building an application and frankly is the only part that matters. Everything else is a waste of your time in boilerplate. For learning how to build software, however, its not a waste of time.
If you have any other questions, please ask. I am happy to answer with my own experience.
I am also actually writing a php framework with a friend of mine. I absolutely can understand what you do.
I thing what you are doing is near mvc. You have the templates as views. And the modules as controller. So I think that is ok. The only thing you need is the model. That would be some kind of active records.
In my framework there are simular concepts, except we are writing our own active records engine at the moment. I think what you do isn't bad. But it's hard to say without seeing code.
I see only one problem you have to solve. A framework should be perfectly integrated. It is always a complicated to make your module look nice integrated without always have to think of module while you are coding application.
Is MVC really effective for a personal framework?
Would it be a bad idea to use a module system?
Yes it is. But MVC is such a loosy-goosy design pattern that you can draw the line between model, view, and controller anywhere you want. To me, the most important parts are the model and the view. I simply have pages, php modules, that generate html by filling in a template from a database. The pages are the view and the database is the model. Any common application-specific code can be factored out into "controllers". An example might be a common, sophisticated query that multiple pages must use to render data.
Other than that I have utilities for safe database access, simple templating, and other stuff.
Did you ever write a framework for yourself? What are your experiences?
Yes. I'm very glad I did. I can keep it simple. I know intimately how it works. I'm not dependent on anyone but myself. I can keep it simple yet useful.
Some pointers (0x912abe25...):
Every abstraction comes with a cost.
Don't get to fancy. You might regret not keeping it simple. Add just the right amount of abstraction. You may find you over-abstracted and something that should be simple became excessively complex. I know I've made this mistake. Remember You-aint-gonna-need-it.
Scope your variables well
Don't load your pages by doing
include_once('...page file ...');
where it's expected that page file will have a bunch of inline php to execute looking up different global variables. You lose all sense of scope. This can get nasty if you load your page file from inside a function:
function processCredentials()
{
if (credentialsFail)
{
include_once('loginpage.php');
}
}
Additionally, when it comes to scoping, treat anything plugged into templates as variables with scope. Be careful if you fill in templates from something outside the page file associated with that template (like a master index.php or something). When you do this it's not clear exactly what's filled in for you and what you are required to plug into the template.
Don't over-model your database with OO.
For simple access to the database, create useful abstractions. This could be something as simple as fetching a row into an object by a primary index.
For more complex queries, don't shy away from SQL. Use simple abstractions to guarantee sanitization and validation of your inputs. Don't get too crazy with abstracting away the database. KISS.
I would say that MVC makes more sense to me, since it feels better, but the only practical difference is that your login.php would contain both the model (data structure definitions) and the controller (code for page actions). You could add one file to the module, e.g. class.login.php and use __autoload() for that, which would essentially implement an MVC structure.
I have refactored a big PHP project to make it more MVC compliant.
I found especially usefull to create a DAO layer to centralize all database accesses. I created a daoFactory function, which creates the DAO and injects the database handle into it (also the logger, I used log4php, got injected).
For the DAO, i used a lot the functionalities of the database (mysql), like stored procedure and triggers. I completly agree with Doug T. about avoid over-abstraction, especially for database access : if you use the DB properly (prepared statements, etc.) you don't need any ORM and your code will be much faster. But of course you need to learn mysql (or postgress) and you become dependant on it (especially if you use a lot of stored procedure, like I tend to do).
I am currently refactoring a step further, using the Slim php framework and moving toward a restfull api : in this case there is no view anymore because everything is outputted as json. But I still use smarty because its caching works well and I know it.
Writing a framework could be a rewarding experience. The important thing to consider is that you do not write a framework for its own sake. The reason one writes a framework is to make development easy.
Since it is a personal framework you should think in terms of how it could help you develop with less hassle.
I do not think a template system is a good idea. Think of it - what is the major benefit of using a template system? The answer is that it helps teams with different skill sets jointly develop an application. In other words, some members of the team can work on the user interface and they do not need to be PHP coders. Now, a personal framework will most likely be used by a single person and the benefit of template system becomes irrelevant.
All in all, you should look at your own coding habits and methods and discover tasks that take most of your time on a typical project. Then you should ask yourself how you can automate those tasks to require less time and effort. By implementing those automation mechanisms you will have to stick to some sort of conventions (similar to an API). The sum of the helper mechanisms and the conventions will be your personal framework.
Good luck.
MVC doesn't work
you don't want to be constrained in the structure of your "modules"; also, keep templates close to the code (the templates directory is a bad idea)
no
re 1.: see Allen Holub's Holub on Patterns. briefly: MVC basically requires you to give up object oriented principles.
Tell Don't Ask is a catchy name for a mental trick that helps you keep the data and code that acts on it together. Views cause the Model to degrade into a heap of getters and setters, with few if any meaningful operations defined on them. Code that naturally belongs in the Model is then in practice spread among Controllers and Views(!), producing the unhealthy Distant Action and tight coupling.
Model objects should display themselves, possibly using some form of Dependency Injection:
interface Display
{
function display($t, array $args);
}
class SomePartOfModel
...
{
function output(Display $d)
{
$d->display('specific.tpl', array(
'foo' => $this->whatever,
...
));
}
}
OTOH, in practice I find most web applications call for a different architectural pattern, where the Model is replaced with Services. An active database, normalized schema and application specific views go a long way: you keep the data and code that acts on it together, and the declarative nature makes it much shorter than what you could do in PHP.
Ok, so SQL is a terribly verbose language. What prevents you from generating it from some concise DSL? Mind you, I don't necessarily suggest using an ORM. In fact, quite the opposite. Without Model, there's little use for an ORM anyway. You might want to use something to build queries, though those should be very simple, perhaps to the point of obviating such a tool...
First, keep the interface your database exposes to the application as comfortable for the application as possible. For example, hide complex queries behind views. Expose update-specific interfaces where required.
Most web applications are not only the owners of their respective underlying databases, they're their only consumers. Despite this fact, most web applications access their data through awkward interfaces: either a normalized schema, bare-bones, or a denormalized schema that turned out to make one operation easier at the price of severe discomfort elsewhere (various csv-style columns etc). That's a bit sad, and needlessly so.
re 2.: it's certainly good to have a unified structure. what you don't want to do is to lock yourself into a situation where a module cannot use more than one file.
templates should be kept close to code that uses them for the same reason that code that works together should be kept together. templates are a form of code, the V in MVC. you'll want fine-grained templates to allow (re)use. there's no reason the presentation layer shouldn't be as DRY as other parts of code.

Categories