This could probably be considered an academic question, rather than a real world one - but throwing it out to see if anyone has any great ideas! We all know that keeping the business logic of an application separate from the presentation is a good idea (I'm looking at web-apps atm), but there needs to be an understanding between the business logic for what HTTP variables to expect (and then process) and the variable names which are sent by the presentation layer.
Is this simply a matter of telling the designer what variable names to use in a template? The template doesn't need to know what the variable names are (unless using them for JS/CSS selectors), so why should they be 'hardcoded' in there. Or should the business logic put the names into variables to be printed out? Another layer of complexity for the templates?
Does anyone have any experience of this, or thoughts on how to deal with it?
Thanks,
Allan
My thoughts ... I guess it depends on the developer. Whenever I build apps, I , as you suggested, seperate the business and view logic, and usualy define a ViewModel. The viewModel then becomes the contract between business logic and the view. This allows both teams (UI and business logic developers) to develop independantly and of course allows easy testing etc..
I appreciate there are various approaches to view logic seperation, but, through experience if you can define a contract bewteen the two (in whichver form it takes depending on what pattern you are using) it makes development easier, especially when you have seperate teams building sperate components.
When I'd previously worked in web-development (currently I'm in admin/support) the problem was that the designers couldn't get their heads around the idea of using placeholders which would be substituted later - and for some complex layouts (e.g. a dynamic accordion type hierarchical navigation menu) there was a chicken and egg problem around designing the parts of the stylesheets which handled animation and functionality vs controlling fonts and colours.
Even with the most capable of designers, the tools they use don't lend themselves to solving the problem.
The approach we ended up taking was that the developers would provide examples of HTML fragments which the designers would then build the pages around, and then the developers would replace the fragments with the dynamically generated content and clean up the style sheets, merging any classes.
It was the most pragmatic solution we could arrive at.
C.
Related
To start with I'm not exactly sure if this question will fit the question model of SO so moderators please close it if it doesn't fit...
I have been reading a lot on MVC and SoC lately and how they relate to programming in PHP and am having some difficulty grasping how the concepts differ to my current programming style. Any application I write uses url_rewrite routes, with the routing handled by a single file which selects the appropriate controller.php file based on the sub system requested. Then within that controller file the final smarty template file is assigned and the PHP file which contains the business logic of the page in question is included into the stack.
The issue I am having is that while I review MVC and SoC information all the examples I see are written as extensive inter-dependant classes and some rather deep namespaces, but when I code I only use objects where I need an object for reusable but distinct code (in line with object examples on the PHP site itself), and so wind up with some code being classed and namespaced nearly 70% of my application remains in the global namespace with no classing. It seems to me that this coding technique still meets the design principal of separation of concerns, though i'm not so sure about being MVC as every example of MVC I can find is built solely out of a very large number of classes.
Could someone please explain if I am way off base here or if I am achieving SoC and possibly even MVC with my current coding and explain to me if embedding the entire application within a range of classes is a requirement for SoC and MVC.
Thanks
OK I usually take on these open ended questions :P
Let me rephrase your whole thing to a new question – and feel free to tell me I am wrong!
I think you are asking - “Is my coding style in-line with best practice for x y z?”
Now look – i have been in a variety of roles, and I strongly believe that no one has ever cracked a complete SoC architecture – at some point there is always a trade-off between enabling someone at the view end to do their job, and someone upstream ingesting the input and making it work such that it ties to the database and logic.
For example - I am actually right now building a system that takes HTML files as input, reads them via PHP. PHP converts the HTML elements to a bunch of JSON and adds logic to that JSON based on x, y and z, then shoves it out to Facebook React components – which converts it all back to HTML / DOM – when you explain to someone that there is a sausage machine that takes, as input, HTML, and outputs HTML, you can see why they might go – holy shit what are you doing!!
Now – why did we do this? Because it made sense for the project, and it made sense for the team. We could have equally used some pre-defined framework and blah blah blah – however this worked for us.
(a caveat here would be, if you need a highly performant application, this might be the wrong approach, however – bear in mind that what you read (inter dependant classes etc.) may also not be performant – optimisation of PHP code is hard work – my advice here is, get it working first, then if the product is successful, pay someone to fix your shitty code – server time is cheap – your time is not)
My statement for you would be, without concrete examples and use cases – people will struggle to comment on your approach – but understand that there are many different ways of doing things and you may see much open source code written in one way or another, but if you write something that achieves a goal, your only concern should be that it is performant and that it has ‘enough’ separation such that your designer can work on design, your coder can work on code and your CEO can look at sales figures.
Hope this helps.
From the information you've given, you're doing a good job. I think you have a grasp at Separation of Concerns and probably MVC. I think you should take a closer look at how things are abstracted in other codebases, how things are modularized, and think about how you would handle things that potentially come up in web development.
What if I want to have some code run before every controller? Or middleware that runs between the request and the controller? Or inject a variable into the view after every controller is processed? How are you separating POST, GET, PUT, DELETE logic but still grouping them within a resource? Some of these can be achieved with your architecture but I think many of the solutions would be cleaner with a class-heavy architecture. Of course, something being cleaner is in the eye of the beholder.
Frameworks released to the public try to be generic and tackle as many use cases as possible. One issue I see is that you make the assumption that the controller file would be called last and then setup the view. So, even though the logic in there is in the global state, it only exists within that file. In essence, the file acts as a namespace. I don't think that's an assumption a generic web framework should make, but it's something you can get away with when writing something for yourself.
I wrote in PHP a learning management system for a small private school. It started a while ago when a lot of programming stuff was new to me. It is mostly scripts and includes based and doesn't contain classes or any MVC style organization, but it has grown big. What I am trying to do is to organize the current code without rewriting, so that it is good for fast iterations.
So far I changed it so that every role has its own folder/index/actions and all of them use one shared lib.php file to do sql queries and other related actions.
I talked to couple of MVC folks and considered PHPCake and Tonic as an option, but those seem to change dramatically what I already have. I am not sure if it just in my practice, but I just don't see how MVC will make it easier for me to develop faster. Can someone give tips or experience advise/opinions or maybe some helpful links. Thanks.
MVC can be a useful framework for developing applications into logically separated components in a somewhat 'natural' way. It can increase your ability to develop quickly based mainly off the fact that some portions of the framework will end up being reusable and allow you to leverage that fact to develop new views and similar quickly. However, it is not necessary to use any particular framework or scheme to develop quickly as it can be done with a properly designed application of any nature.
An important thing to consider when developing an application in such a manner is code reuse. For example, making it simple to display pages with common layouts through a centralized mechanism, or having user-related functions placed into a user class/function set which can be reused site-wide instead of having individual functionality to handle it on each page.
In terms of modifying an existing application, I would focus on trying to centralize the components you are able to and making use of those components henceforth. This also makes modifying routines simpler because instead of potentially changing functionality on many areas of the codebase, you can change it in a single location and effect the application as a whole.
Trying to make a pattern fit a problem is a very silly approach. Patterns are what code is not what what the code should be. In any object-oriented project presenting a user interface there will be instances of models, views and controllers - but there will also be lots of other patterns in the code - observers, decorators, iterators and more. They are useful learning constructs (e.g. "Here's how to implement a factory to build objects from relational data") and (human) language constructs (e.g. "That database connection class should be implemented as a singleton"). They are not design constructs.
so that every role has its own folder/index/actions
Unless you've got a rather unusual definition of 'role', this architecture makes no sense. The most common criteria for dividing up high-level functionality are separation of concerns and grouping around common data sources.
You've mentioned frameworks - trying to adapt existing code to fit into a framework is usually a bad idea - it won't fit. They can be of benefit in structure your application and reducing the amount of effort if you sse them from the start of the project. Not from the middle / end.
Put the new code you write under test. As the old code isn't, put it under test part-by-part as well. At the moment you've put everything under test, you should be fine for faster iterations.
The web-based application I’m currently working on is growing arms and legs! It’s basically an administration system that helps users to keep track of bookings, user accounts, invoicing, etc. It can also be accessed via a couple of different websites using a fairly crude API.
The fat-client design loosely follows the MVC pattern (or perhaps MVP) with a PHP/MySQL backend, Front Controller, several dissimilar Page Controllers, a liberal smattering of object-oriented and procedural Models, a confusing bunch of Views and templates, some JavaScripts, CSS files and Flash objects.
The programmer in me is a big fan of the principle of “Separation of Concerns” and on that note, I’m currently trying to figure out the best way to separate and combine the various concerns as the project grows and more people contribute to it.
The problem we’re facing is that although JavaScript (or Flash with ActionScript) is normally written with the template, hence part of the View and decoupled from the Controller and Model, we find that it actually encompasses the entire MVC pattern... Swap an image with an onmouseover event - that’s Behaviour. Render a datagrid - we’re manipulating the View. Send the result of reordering a list via AJAX - now we’re in Control. Check a form field to see if an email address is in a valid format - we’re consulting the Model.
Is it wise to let the database people write up the validation Model with jQuery? Can the php programmers write the necessary Control structures in JavaScript? Can the web designers really write a functional AJAX form for their View? Should there be a JavaScript overlord for every project?
If the MVC pattern could be applied to the people instead of the code, we would end up with this:
Model - the database boffins - “SELECT * FROM mind WHERE interested IS NULL”
Control - pesky programmers - “class Something extends NothingAbstractClass{…}”
View - traditionally the domain of the graphic/web designer - “”
…and a new layer:
Behaviour - interaction and feedback designer - “CSS3 is the new black…”
So, we’re refactoring and I’d like to stick to best practice design, but I’m not sure how to proceed. I don’t want to reinvent the wheel, so would anyone have any hints or tips as to what pattern I should be looking at or any code samples from someone who’s already done the dirty work? As the programmer guy, how can I rewrite the app for the backend and front end whilst keeping the two separate?
And before you ask, yes I’ve looked at Zend, CodeIgnitor, Symfony, etc., and no, they don’t seem to cross the boundary between server logic and client logic!
You and everyone else with a brain is asking this question and it's a sticky one. A really good Information Architect thinks in terms of usability, behaviors and flow, although he/she may not even know how to use design tools or be able to draw or program. If they can get an interface into a sketch, the designers can make it pretty. Let the designers do the looky feely STATIC stuff--that's what they are good at. Provide IA with a library of front-end behaviors that they can specify for screen objects. They don't implement this stuff, they only USE it. This is much easier if you use a front end tool such as JQuery, and it's great if you have a front end guru who understands both design & the back end quite well. Separate your javascripts into their own directory and always link them as external files. All the PHP frameworks have methods to do this dynamically. I have toyed with the idea of a config structure that maps files to all the front end stuff that they load so each individual view only loads what it needs. But you are absolutely right: There is a whole nother sub-MVC for the clientside that lives primarily within the views of the overall MVC. I think you can partition off the Ajax stuff (when the view needs to refer back to the server) I document Ajax controller methods as ajax methods and don't call them otherwise. A lot of it is having everyone on your team buy into the division of labor paradigm. It will just cause them to write more decoupled reusable code whatever framework you ultimately choose to hang it on. And you're right, you can do the front end encapslation with all of them, but NONE of them enforce good front end encapsulation, I think that's still in the realm of DYI. Good luck.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Why should I use templating system in PHP?
I was just curious as to how many developers actually do this?
Up to this time I haven't and I was just curious to whether it really helps make things look cleaner and easier to follow. I've heard using template engines like Smarty help out, but I've also heard the opposite. That they just create unnecessary overhead and it's essentially like learning a new language.
Does anyone here have experience with templates? What are your feelings on them? Are the helpful on big projects or just a waste of time?
On a side note: The company I work for doesn't have a designer, there are just two developers working on this project charged with the re-design/upgrade. I also use a bit of AJAX, would this have issues with a template engine?
Not only does this practice make the code look cleaner, it also has many long term and short term benefits.
You can never go wrong with organizing code. First off it makes it much easier to maintain and easier to read if someone else has to pick up after you. I have worked with Smarty before and it is nice, it keeps the designers work from interfering with the program code.
Using template systems and frameworks would make it much easier to accomplish tasks. There is a rule of thumb you can follow which is DRY (Don't Repeat Yourself). Frameworks help you achieve this goal.
You may want to look into MVC, this is the model that these frameworks are based off of. But you could implement this design structure without necessarily using framework. Avoiding the learning curve. For frameworks like Zend, the learning curve is much greater than some other ones.
I have found that Code Igniter is fairly easy to use and they have some VERY helpful video tutorials on their website.
Best of Luck!!
Actually it's the business logic that needs to be separated from the views. You can use php as a "template language" inside the views.
You can use ajax on any template engine i think.
Edit
My original response addressed the question whether to use a template engine or not to generate your html.
I argued that php is good enough for template tasks, as long as you separate business logic from presentation logic.
It's worth doing this even for simple pages, because it enables you to:
isolate the code that is the brain of your application from the code that is the face, and so you can change the face, without messing with the brain, or you can enhance the brain without braking the looks
isolate 80% of bugs in 20% of your code
create reusable components: you could assign different presentation code to the same business code, and vice versa;
separate concerns of the feature requests (business code) from the concerns of the design requests (presentation code), which also usually are related to different people on the client side, and different people on the contractor side
use different people to write the business code and the presentation code; you can have the designer to handle directly the presentation code, with minimal php knoledge;
A simple solution, which mimics MVC and doesn't use objects could be:
use a single controller php file, which receives all requests via a .httpdaccess file;
the controller decides what business and presentation code to use, depending on the request
the controller then uses an include statement to include the business php file
the business code does it's magic, and then includes the presentation php file
PHP is a template engine (or if you prefer, a hypertext preprocessor). When HTML is mixed heavily with PHP logic, it does become very difficult to maintain, which is why you would have functions defined separately to build various parts and simply build the page from short function calls embedded in the HTML. Done like this, I don't see much of a difference between Smarty and raw PHP, other than the choice of delimiters.
Separation of concerns is a very important tenant to any type of software development, even on the web. Too many times I have found that people just throw everything into as few files as possible and call it a day. This is most certainly the wrong way to do it. As has been mentioned, it will help with maintainability of the code for others, but more than that, it helps you be able to read the code. When everything is separated out, you can think about easily.
Code Ignitor, I have found, has been the easiest to learn framework for working with PHP. I pretty much started my current job and was up and running with it within a few days, from never having heard of it, to using it pretty efficiently. I don't see it as another language at all, either. Basically, using the framework forces me to organize things in a manageable way, and the added functionality is anlagous to using plugins and such for jQuery, or importing packages in Java. The thought that it's like learning another language seems almost silly.
So, in short, organize organize organize. Keep in mind, though, that there is a level of abstraction that just becomes absurd. A rule of thumb is that a class (or file in our case) should do one thing very well. This doesn't mean it is a class that wraps around print, but takes a string, formats it using a complex algorithm and then prints it (this is just an example). Each class should do something specific, and you can do that without any framework. What makes MVC great, though, is that it lets you organize things further, not just on the single class level, but on the level of "packages", being Model, View, and Controller (at least in the case of these frameworks; there are other ways to package projects). So, now you have single classes that do things well, and then you have them grouped with similar classes that do other things well. This way, everything is kept very clean an manageable.
The last level to think about once you have things organized into classes, and then packages, is how these classes get accessed between packages. When using MVC, the access usually will go Model<->Controller<->View, thus separating the model (which is usually database stuff and "business" code in the PHP world), from the view (which usually takes information from the user, and passes it along to the controller, who will then get more information from the model, if necessary, or do something else with the input information). The controller kind of works like the switchboard between the two other packages usually. Again, there are other ways to go with packaging and such, but this is a common way.
I hope that helps.
Smarty and other php template frameworks really do nothing more than compile to PHP anyway, and they also cache their results in most cases to allow for faster processing. You can do this all on your own, but if you ever look at the compiled templates that Smarty generates, and compare to the original Smarty template you create, you can see that one is far more readable than the other.
I write mostly mod_perl these days and started using templates (HTML::Template) halfway through our ongoing project. If I had to make the decision again, I would use templates right from the start - rewriting later to use templates is kind of tedious, though rewarding because you get nicer and cleaner code. For anything bigger than 2-3 pages in php, I would also use some template engine.
One big advantage of a templating engine such as Smarty is that non-developers can use it to embed the necessary logic that is used on the front-end (one really can't separate logic and display on all but the simplest sites). However, if the developer is the one maintaining the pages then using PHP would be preferable in my opinion.
If you separate out large logic blocks and maintain a consistent patten for looping and for-each flow control statements (i.e. don't use print statements, or only use print statements for one-liners, etc.) Then that should be okay.
Long time lurker, first time poster...
I'm now at the point where I'd almost call myself a professional grade PHP programmer and have a lot of code I re-use in various projects. Also, a lot of Open Source packages I've worked with use the MVC model and as a result I've done a lot of research recently into how it all works so I can better edit them as required.
At this point, I'm considering taking a bare-bones MVC framework (from a tutorial) and extending it as required for my forthcoming programming jobs.
My question is whether the MVC model with pretty much all application logic separated from the presentation layer is considered best practice over a well structured OOP website with coding on the page as necessary e.g setting function variables.
Or will I run into issues when I want coding flexibility e.g.
using something like PHPthumb for a gallery where I want different output
sizes on different pages and currently set parameters in the head
of the page
a contact form with x fields and a feedback form with y fields - will this require 2 differrent models rather than a generic form class again with some parameters set in the head of the page
some pages requiring ob_start() and ob_flush() but not others?
Please don't tell me not to build my own framework - I'd rather know how each little bit works than use a slab of code I know nothing about - I'm really interested in the opinion of people who have gone this route and build sites every day. What are the real pros and cons of this over plain (but well structured) OOP and bunch of pages to a site as opposed to 1 index.php page and separate files.
Cheers,
Niggles
I know you say you don't want this advice, but don't write your own. The first thing I've done at every single job I've ever worked at is picked up some existing code or framework, often commercial but highly modified, and begun maintaining it. You'll seldom get the option to write your own, and doing so is a bad idea. It's hard, expensive, and somebody else has already written a better MVC PHP framework than you're likely to write.
There are literally dozes of mature PHP frameworks, most of which have been around for over a decade. Choose one of them. It doesn't matter which one - they're all maintained by a dozen people at least as smart as you who've been writing MVC frameworks a lot longer, and have spent months or years refining their frameworks and listening to user input.
All that said, if you want to write your own on your own time, as a hobby, so you're not wasting your boss's money, then by all means. There's a huge variety of interpretations of MVC. Some frameworks view views as basically templates. I personally think you can throw as much raw PHP in there as you'd like, so long as it's purpose is display, and you do the usual smart things like distilling out shared code into functions. Some frameworks have virtually no business logic in the models (where it belongs IMO) but have very heavy controllers. The best thing you can do is try other frameworks and see how they work, and which you like best, and decide what you'd like to see changed. Then, set out to change it in your own.
You say you're almost ready to consider yourself a professional? The hardest lesson I had to learn was that professionals don't write their own low-level libraries. They don't reinvent the wheel on the company buck. They use off-the-shelf components and get the job done today, rather than a month from now. You don't want to use a slab of unfamiliar code? That's the biggest part of your life to come as a programmer - get used to it.
Writing your own framework is great for your own edification and for truly understanding the language.
Personally I find its as time consuming using a third party framework as it is to write your own. Yet I have total control of my own code, not something you can claim with any third party framework.
I also think many MVC frameworks are very resource intensive. For high volume sites you need to be prepared to throw hardware at them to get them to run nicely. For low volume sites (the majority) the rapid development of a third party MVC framework is a huge bonus.
So in my opinion if you have the time, roll your own and be proud of it. Just make sure you learn from others especially where security is concerned.
It all depends on what are you project requirements are and how you design your application objects. MVC do not force you to use an specific class or view design, It will only provide you with an architecture that will help you isolate the business logic from the presentation and the data layer making you application more scalable and easy to test.
In MVC you are not tied to one view per controller you can use as many views as you want per controller since every exposed method can call a view itself and control how it looks and behave based on the business logic you define. That said you can have 2 methods to return a full size image and a thumbnail without having to create two pages. You can set everything on the view from the controller, header meta-data, scripts, links, theme, content, etc...
In regard to the models, it again depends on your project requirements but definitely, in any case, if you have several pages with different purposes and they require to modify different data sources there should be a model for each one of them and what you can do after is to create a class that encapsulates the form functionality by calling the model for getting the fields to create form, get and save the data. This is just an idea you can do it in a lot of different ways, that is the beauty of OOP.
In the end it is not a matter of comparing a well structured OOP site against an OOP MVC site, It is more an analysis of the time and effort you spend working on building a site architecture that can succeed in isolating concerns at the same time it still readable and scalable while it meets your project requirements.
If you want to get more ideas about design patterns you can use google MVP design pattern and/or MVVM design pattern.
I have written my own framework. It does not take time to create the architecture and raw code. It's great if someone writes there own framework. But If documentation is not proper than definitely pain in asses. Completely depends upon yourself. I have written mine as well. It took almost 7 days to make framework QA ready :). but the main issue is to get satisfied by the piece of code you write in your framework. You would always like to improvise your framework and wanted it to be best ever. BLAH! BLAH! If you wish to write your own and you are confident enough for sustenance. GO for it.
Any MVC -- homegrown or not -- will allow you flexibility and re-usable code.
ob_start() / ob_* calls are no problem, they go in your model and called from your template, e.g.:
Hello <?php echo $this->getFormattedName(); ?>
where your model is
function getFormattedName() {
ob_start();
echo '' . $this->getName() . '';
$return = ob_end_clean();
return $return;
}
For your form scenario, you would probably want an abstract form class that defines how a field is made and its validation, then each specific form would extend your abstract.
You may want to consider using something like Zend Framework -- while it's an MVC library in its own right, you can pull in single components super easily (for example, you can pull in Zend_Form and Zend_Mail for your contact and feedback forms & validation and use your own models for everything else). This would also give you the extra benefit of having a fallback when/if the time comes when your homebrew MVC framework starts to outgrow its original design. Or, at the very least, speed up your development time so that you're not held up for days because you suddenly realize you need an e-mail model.