Web Development - The Line Between Code and Content?
markmcb asks: "I help design a LAMP web site and I'm constantly plagued by trying to decide on what level should I separate functional code and markup. Depending on what you read, some say embedding HTML in your PHP scripts [or Perl, or Java, or Ruby, or Python, etc] is bad while others say it's no big deal. However, seldom are any practical applications of such code cited. How is your site built? Do you mix HTML with your code? If not, how do you overcome the simple and easy method of doing so? Lastly, what performance gains/losses have you noticed by doing so?"
I taught myself to script perl a few years ago, and no one told me one way or the other. So I decided to embed the html a bit in the code, and I really can't think of a good reason why it would be bad to mix the html, unless its for the sake of the clarity of the code.
I had to implement an intranet site using zope/plone which seemed to prefer a separation, but I saw no reason for it, except the obvious use of templates, and just went ahead business as usual. So i think this is just a matter of preference.
I generally find it's best to remove all code from html as then it becomes portable to other projects easily...i'm sure this doesn't satisfy all your questions but i like to seperate functions from display, same with UI programming.
I personally find it easier to integrate (X)HTML with my PHP. When I've needed to store them seperately, though, I've seen no performance differences and I highly doubt that there would be anything significant. PHP is fast.
Then again, I've never used Perl, Python, or Ruby for web development. Perhaps they're different.
ROMANES EUNT DOMUS
I use templates containing the HTML nowadays unless the HTML is very simple. There's a very nice Perl module, Text::Template, for using templates - you can embed Perl fragments in them too if you wish.
I imagine that PHP and Ruby have similar things.
Seperated: If you want something modular and scalable (but slower)
Embedded: If you want something faster and easy to write (but not as scalable)
MABASPLOOM!
"How is your site built? Do you mix HTML with your code? If not, how do you overcome the simple and easy method of doing so?"
Simple I don't. I deal with a higher-level language (DSL) which then generates server-side code (XHTML, CSS + whatever else is needed. e.g. media files). More work on one end for simplicity on the other.
Business logic would use the driver API, making data requests that were resource-neutral. In other words, the business logic didn't care where the data came from, only that it got what it asked for. Different business functions were isolated, and each presented its own API to the applications. The APIs themselves conformed to a specification. That way, apps written by different developers could perform the same business functions without recoding everything. The applications made requests of the business logic according to the spec, then presented the results to the clients for formatting (web, RSS, PDF, whatever). Uniform data structures were used throughout.
You may not need that level of sophistication, but it sure as heck helped us prototype, isolate employee functions and skills, etc etc. It allowed us to run multiple OSes (Windows, Linux, Solaris) and multiple languages (.NET, VB, and Java) together seamlessly. It also helped when doing architecture, since it forced us to think about what a particular piece of code was really doing. Under our scheme, PHP would be layer 4, and HTML layer 5, so we would separate them. You could just as easily use PHP to generate XML, for example.
This post expresses my opinion, not that of my employer. And yes, IAAL.
For the project we're working on, we are combining several bits of XML data and using an XSL template to display the HTML. This helps seperate the data from the markup. That way, your PHP or Perl would be responsible for getting the data (in our case, XML from web service calls and XML config files), handling user input, and running the XML/XSL transform. This solution works for us because we can dynamically call different XSL templates depending on the skin we want to display to the user, but the data always coming from the config files and web service calls always stays the same and doesn't care about the markup. The downside here is that this method requires that any database calls or business logic is returning XML. It works great for us, since we're moving all of our logic into a web service layer, and the services always return XML. This might require more architectural work than is necessary in your case, but if the web app is big enough or complicated enough, this method provides some great decoupling.
People will always tell you to "separate logic from presentation" and that is good advice - to a certain extent. I don't think that this is correct all the time, however, because it is not a correct statement per se because the two cannot always be separated. However, they usually can and usually are, and web pages are a good example of this. But what does "separate" mean? Does it mean physically moving your presentation to another file, generating it, etc.? There are many different ways, all of which work best in certain situations.
Here's what you should worry about instead:
1) Is the program readable?
2) Can you easily make changes in the program without having to change too many other parts of it?
3) Are you having to rewrite the same code too much?
Those are some pretty basic computer programming design concepts, and if you apply those, you'll find that the answer should be pretty clear. Just keep everything clean and life will be happier.
Did you ever notice that *nix doesn't even cover Linux?
My preference is to use Mason, a perl... well, it's a development framework to some, but it works as a pure templating engine as well. It allows embedding of perl snippets (and blocks, but that's best to avoid) in content documents. I prefer that balance. Occasionally you need display logic that can only be accomplished in code, it's unavoidable. So, my breakdown is: prepare data-structures the display will use, as shallowly as is reasonable for the display code, and then pass that along. Put a small chunk of logic into the content. That way, if a designer needs to come along later and change things, the place, if not how exactly, is much more transperent to them. If they realize they need help, they can ask for it or try it themselves. You keep the project in a revision control system, right? ;)
I worked for this web shop which chose to seperate HTML from the code so they could hire cheap designers to draw up the HTML to make it look nice. Ended up no matter how simple we made the templates, and how much hand holding we had to do to show them how to do it, they *always* fucked it up somehow. They ended up hiring more experienced designers, paid a higher hourly rate but saved in the long term.
I think it's horses for courses, some quick projects can benefit from mixed source. Some 'enterprise' level applications really call out for seperation. Pick and choose.
Task Mangler
For me, I try to look at it from a practical perspective. I don't separate code & content because of some idealogical reason (well, OK, I do... but I use the following thinking to help me determine how to implement it). Instead, I separate code & content because I know that inevitably, some non-geek is going to need to change the look & feel. And I want to expose the least amount of code possible, so that they can do the least amount of damage.
Therefore, here is how that plays out. First, I create everything procedurally, one huge page, HTML & PHP & CSS & JavaScript all mixed in together. Then, once I am no longer iterating through revisions frequently, I start to pull out the non-HTML bits. The CSS & JavaScipt are usually the first to go, with HTML tags to pull that code back in. The PHP gets two run-throughs. First, I move repetitive code into functions (I don't do a lot of OOP). Second, I break the PHP code into logical include files. So for example, I typically have a handful of libraries that set up the page. Those go into setup.php (database connections, handling the on/off issue with addslashes, and so on). Anything that is page-specific goes into another include file. What I'm left with is HTML with a few short PHP echo statements. For example, something like this might appear right after the BODY tag:
...just to output any status messages that my code generated. And then something like this might appear anywhere I had a PHP variable to drop into the page:
...and so on. The basic gist is that I offload the code into include files, and those files generate variables that contain whatever content is needed for display. The HTML page itself merely has some PHP include statements and a few PHP variables sprinkled throughout the page. By doing this, some random artsy-type or client who noodles with the HTML can usually still revise things without damage. They usually understand what they're seeing. And that's all I'm aiming for. I don't try to go any more hardcore than that -- no abstraction layers, etc. Oh, also, I try to avoid having more than 1 level of included files. In other words, my included PHP code does not use include() to pull in even more files. The nesting on some projects just drove me a bit nutty, so I try to only go 1 level deep. I rarely keep to it, but it's an ideal. :)
My Greasemonkey scripts for Digg &
For larger web sites I separate the code into a Presentation Layer and a Business Layer.
The Presentation Layer is simply PHP/JSP/whatever-code embedded in HTML. The Business Layer does not contain any markup at all, being mostly a wrapper around database calls but with an API that fits the application. Could be written in another language. For instance, for a web site that requires user accounts, User objects are owned by the Business Layer.
Then let the Presentation Layer have a common library for common markup actions, where some of the look of the web site is defined.
Ifever you have misdesigned the system so that the Business Layer has to do markup anyway, it should use functions from that library to do it.
"We mustn't be caught by surprise by our own advancing technology" -- Aldous Huxley
BTW, if you're looking for a nice framework for Java web development I highly recommend Stripes. I stumbled across it last year and it is much nicer to use than Struts!
My web pages break down as such...
I build a content page using HTML and CSS. No tables unless it is to display data. Trying to make it as clean as possible.
I then move any HTML that repeats throughout the site (usually header and footer) into includes.
I then create the functions that will build my menus and populate the content. I put these into classes.
Call the class in the header include. Call the functions where apporpriate, and viola! I have five documents: CSS file, header, footer, class/function file, and then all the other pieces that are left in the original HTML document. Usually I will end up with a six document that has all the javascript, if necessary.
Technically, you could build the header and footer to be functions, and cut down to two documents, but I have found that to be a bit of overkill, as usually the stuff in these are not very dynamic.
Now, there may be some HTML in my functions. After all, if the function is going to put out HTML, then it probably needs HTML in it. But I try not to build any function-type code into the HTML. The nice thing about this set up is the core HTML document needs virtually no maintenance, and can be used for every single content page, assuming you are passing which page you need to the appropriate function.
The world moves for love. It kneels before it in awe.
PHP is, for better or worse, easy for both coders and designers.
That means if you are a coder you can create pages with PHP that output from script.
But if you a designer you sprinkle PHP into your HTML where you need dynamic content.
If you are truely trying to keep content and design seperate, then you need to create templates (that designers build) that PHP calls forth and populates with content.
The Smarty template engine offers a flexible and powerful tool for PHP developers.
Where/when I choose to use templates versus embedded code depends on where in a web application the page is viewed. For example, I would use templates on the frontend of complicated sites that require pages to have different page displays, such as a newspaper. A regular news story may display differently from an editorial or op/ed piece. I also think the frontend of a website should be flexible because redesigns happen often.
But I embed HTML on the backend because the admin control panels are more functional than asthetic. Also, the backend pages are more critical than frontend pages and I want admin pages to be self-contained (not reliant on templates that may or may not work or contain errors).
If a user screws up a frontend template, the worst thing that can happen is that the page is unavailable until fixed. But if a user screws up a backend/admin page template, you're can't even access the backend to fix the problem.
Separation is good. I can trot out the old "let coders code and designers design," but I often do both, and there are other benefits. You should look at model view controller. You don't have to drink all the MVC kool-aid to get good ideas from it.
Wonder why Slashdot looks like ass? I've spent a lot of time hacking Slash source and, until their recent refactors (and maybe even now) there was markup everywhere in the Perl. It made a redesign impossible without actually writing code, and possible introducing bugs.
MVC says that the presentation layer should be separate from the rest of the application. If you think about it, that's the same idea as keeping presentation (e.g. CSS) separate from content (e.g. XHTML). That idea has clearly won out.
Performance can be a factor for smaller systems, but if you cache your templates or have them precompiled (e.g. JSP) it helps. Also, programmer efficiency is almost always more important than code efficiency. Keeping the controller code and the view separate allows you to find and fix code bugs without wading through all sorts of presentation logic. Who cares about how a nested list is constructed in XHTML when you're trying to find out why your app is barfing?
This isn't as much "normalization" as it is "don't take so many drugs when you're designing tables."
I use the Model View Controller design pattern for UIs. I would suggest you do the same. The View is your pretty HTML stuff, the Model is the crap you want to display, and the Controller is where the code goes to fetch that content and save user input.
"Avoid employing unlucky people - throw half of the pile of CVs in the bin without reading them." -- David Brent
There is a PHP MVC framework fore you here.
"Avoid employing unlucky people - throw half of the pile of CVs in the bin without reading them." -- David Brent
The more proficient you are in web-based languages, the easier it is to separate stuff:
At the bottom you just have a mashup of PHP and HTML using one file per page, with the odd file include for a header or whatever. I started out doing PHP by trying to fix something written this way; it's an easy way of learning what to avoid.
One up from that is separating the layout into CSS, which is pretty obvious.
From there you can move the logic behind the dynamic content into separate files, by using includes or classes or whatever. This is the most common way from what I've seen.
If you want to take it to extremes, then you can get XSLT involved. Probably overkill for a lot of things since it involves juggling 4 languages at once, but I haven't tried it so I can't say whether it's worth it.
I use eGroupWare which was forked from phpGroupWare. Both of these have a utility called "eTemplates" which does all the HTML for you. Try it, you'll like it, productivity is awesome, something like several pages of working, tested, debugged, HTML per day.
Well maybe not so simple, I guess I'll leave that up for you to decide. The answer though, whichever system is easier for you (and your team) to work with and maintain.
On many small projects where I'm the only developer, doing both logic and layout, I had no problem keeping everything embedded. Now, for me personally html is a lot easier to look at in blocks, for example
print EOF
blah blah blah
blah
blah blah
EOF
instead of
print "blah blah blah\n";
print "blah\n";
print "blah blah\n";
So I'd often do that.
However, I also have worked with people I didn't want anywhere near my logic. So I'd use templates and only give them access to those (helps when you're both sysadmin and developer).
Much like the various languages out there, your development style is often something that falls under the category of "right tool for the job".
Embedding everything in your code will make it more difficult for people to come behind you and make updates, especially to layout. Maybe even more difficult for you to edit them yourself after not touching it for a few months/years.
On my personal site, I embed because it's easier and I'm not planning on changing my stuff any time soon. Not to mention that the code is quite simple in nature as well. For work, we have templates and do a regex search/replace for the content.
Partially because customers are quite fickle, I'd recommend _not_ embedding the HTML. As what will you do *when* the customer comes to you and says that they've redone the look and feel of the site.
If you used templates, then the change would pretty much be replacing the old templates with there new counterparts. If you embedded, then you got some long, monotonous work ahead of you.
Embed that shit to keep your job or if you will only be the one maintaining and the applicaiton doesn't grow too much. It's much harder to maintain especially as the application/site grows. Seperate it if you want to be able to scale it to enterprise level apps. My preference is to seperate them strictly becuase seperating content from code is much cleaner.
-- Brought to you by Carl's JR
I've tried sticking to MVC in a desktop application I'm working on, and I've found it quite hard to integrate the three layers. Model is something you would have to have anyway, it's your data structures and business logic, so it's not an issue. View is usually going to consist of some UI widgets, so as long as you're not rolling your own controls, you won't be spending too much time there. But the Controller give me brainache, because it ends up responding in complex ways to multitudes of events, passing control back and forth between the M and the V. Even though the events themselves are simple, the controller is a tangle. For a while I tried splitting the controller into two separate layers to simplify each, but all I got was lots of pointless forwarding of control between the layers. I don't know if it's supposed to be this hard, or if I'm misunderstanding something fundamental. Sigh.
"Only the small secrets need to be protected. The big ones are kept secret by public incredulity." - Marshall McLuhan
If you're using PHP, there is an excellent library called Smarty. It makes using templates very easy.
With Smarty you can do something like this:
template.tpl:
For your PHP it's simply:
With this I can easily change the layout later. No messing around with trying to find all the embedded html.
Smarty also allows you to include other templates from within the template. There are tons of features in Smarty, it greatly improves my productivity.
"It ain't a war against drugs.it's a war against personal freedom" --Bill Hicks
If you care about accessibility (blind users for instance) then you have to seperate. Frankly, it's easier to do anyhow. Build the code first and output the data you need. Worry about how it looks later. If you are building a standards-based accessible website, the data will be output then the CSS will tell it where to go and how to look.
I use three levels of coding:
.php or include files.
1. The layout (template)
2. The content
3. The code
The code is obviously the dynamic portions of a site, consisting of PHP and seperated into either
The content is pure html, and is stored as html formatted include files, or as database entries in a CMS.
The layout (or template) is a hybrid, but primarly HTML. I use a php script to load the code and the content, then finally the layout. The "hybrid" mixes a little PHP so that things like randomized images, banner ads, date, personalized messages, etc can be easily inserted into the template.
I use output buffering on all the code and run it all through a cetral script. That way if after the fact I need to make dynamic changes I can. This central script is what ties the three pieces together. This also allows me to alter any portion of the site on the fly for quick and dirty fixes.
I personally don't buy into the pure CSS stuff, because it is a pain-in-the-ass, but I try to get the code as clean and maintainable as possible. For the most part it has worked well over the last several years that I have used this methodology. I have easily updated sites I worked on 5+ years ago.
-MS2k
Recently, I had to develop a web interface to a firewall (based off smoothwall). I decided to split the interface and implementation so I implemented the interface in C and used libtemplate for the html/js stuff.
An example of this implementation is the web interface for my (crappy, mostly not working, hard to compile) cctv program at http://devsec.sourceforge.net/
In the source tarball the web interface is in the "devsec/web_interface" directory.
The reason I did this was to allow the web developers to create different interfaces without being able to screw with the backend.
it is only after a long journey that you know the strength of the horse.
Instead of busting my head trying to make PHP and HTML co-exist, I'd just FOPEN the template and parse it for "" type tags and replace those with the PHP output.
Lately, I've drifted toward embedding HTML or XML in the PHP and then using big monster functions in APIs. This is also handy for the occassional instance where PHP won't get the job done.
In some instances, there just is no choice. You have to hodgepodge everything together and make it work.
I scream. You scream. I assume that means we're both acquainted with the problem. We proceed.
So many people these days have bought into the Smarty templates stuff. But what they have forgotten is that PHP is perfectly good as a template language. Why are they using a whole separate language to do a job that the very language that the 2nd language is written in can do just as well?
/>
I think it's that people are stuck on such total and complete separation of "logic" and "display" that they have this erroneous idea that the only way that can be done properly is to use two separate languages.
But ask yourself, is
{Loop One $LoopVar1}
<tr><td>{$LoopVar1}</td></tr>
{/Loop}
any different to
<?php
foreach($One as $LoopVar1)
{
?>
<tr><td>{$LoopVar1}</td></tr>
<?php
}
?>
The answer I hope you see is, YES, the first one is heaps slower because the page has to be parsed for the second language and then executed either in that language, or more commonly TRANSLATED into PHP and executed in that instead!
The deal is, separate your Business/Application Logic from your Display Logic, but you don't need two languages to do that.
Sure if it makes it easier and faster for you then you might have some short hand notations to reduce coding, stuff like
{$Foo}
which is replaced with
<?php echo htmlspecialchars($Foo) ?>
or
<form:input type="date" name="Foo"
which is replaced with a text input with a value of $Foo and a calendar date picker button, these could save you a few minutes coding and also makes it much cleaner for the designer.
But stuff like
{If Foo} stuff {/If}
or
<loop var="Blah"> stuff </loop>
is just inventing another syntax for the hell of it, it gives you no advantage, and infact probably increases the amount of code you have to write.
Some people will say here that "oh designers shouldn't deal with PHP". But what they fail to realise is that most designers use "WYSIWYG" tools, principally Dreamweaver for the professionals (as much as hand coding is desirable, lets be realistic, graphic designers seldom do that). And here's the thing, Dreamweaver will do a much better job if the page contains some PHP than if it contains an arcane template language, even one as popular as Smarty. They are LESS likely to break stuff, and infact more likely to UNDERSTAND how the code works if it's in PHP and not in a template language.
Here are a some simple rules..
* Have a minimum of 2 main files for each "page".
* The first contains your application/"business" logic for the page, it processes, queries, sets everything up for the second page.
* The second page contains your HTML and the minimal set of PHP to display that, you can use if, foreach, for, echo and the various formatting functions (htmlspecialchars, number_format etc) but that's about it unless you have a good reason.
* Don't put html in strings. I don't want to see echo "<strong>Foo</strong>"; One exception to this is where it will stop the creation of invalid (or undesirable) HTML nesting in your source file because of some conditional output of extra bits of HTML, the reason for that is so it doesn't screw up in Dreamweaver or intelligent editors which can match tags - this will most often happen if you are making multi-column tables and need to output extra tr's based on some modulus of the record number in a loop.
If you follow this you have cleanly separated logic from display and your designers can now easily work with the display source.
What I've said here isn't just specific to PHP of course, just it's where I see this sillyness the most.
NZ Electronics Enthusiasts: Check out my Trade Me Listings
The second example should be of course
<?php
foreach($One as $LoopVar1)
{
?>
<tr><td><?php echo $LoopVar1 ?></td></tr>
<?php
}
?>
------
this here is some extra text because slashdot thinks I'm being lame with all the whitespace in the above.
NZ Electronics Enthusiasts: Check out my Trade Me Listings
"I've tried sticking to MVC in a desktop application I'm working on, and I've found it quite hard to integrate the three layers."
/. poster).
Allen Holub agrees with you. So do others TOP may be an alternative (Tablizer is a
I'm part of a student-run group at my high school that is in charge of developing and maintaining our school's website, servers, and other infrastructure. This past fall, we began redoing our school's site which, up until that point, was a mish-mash of ASP and HTML. The code was ridiculous - in fact, if we ever get bored, we like to look at the old code for a good laugh. However, we put a lot of thought into different techs that could be used to redo the site. We considered PHP, ASP, Ruby-on-Rails, Python, and different Java solutions. In the end, we chose Apache Struts - it offers an incredible level of abstraction, but it works wonders for development.
Struts works by seperating business logic, actions, and markup. If, in the future, we decide we want to ditch Struts, we can keep the BL and the markup and throw out the actions for whatever we choose to replace it with.
More importantly, however, this allows us to keep code and markup seperate, allowing the backend team to tweak the code as they see fit and the layout team to likewise play with the JSPs.
In my personal practices, I generally do my damndest to keep code and markup seperate. If I'm using PHP, for instance, I'll write a simple template class that I can use to feed data into HTML without fusing the two together. It keeps things organized and (most of the time) headache-free.
I hope I've offered some useful insight - best of luck to you.
-WeAz
If your businesslogic breaks when you change the site layout then embedding HTML in your business logic clearly was a bad idea. Doing so gets you up and running soon but you pay the price later when doing maintenance.
Putting some time and effort in separating logic and presentation is not a novelty. The MVC pattern dates from the seventies. The n-tier server architecture was invented shortly thereafter. These two are now well accepted architectures for separating logic and presentation.
As for performance. Code that mixes everything together tends to be naive in multiple ways, including performance, security, extensibility, etc. Optimizing performance generally requires using caching, pooling and other types of strategies. These are hard to retrofit in monolithic single tier systems. Again there's no absolute truth here: you just may be the genius that gets it right in one go.
So it all depends on the question are you the guy who's doing the maintenance and/or will you be there when the shit hits the fan when somebody else tries to do it for you. If so, you are probably better off doing a proper job. On the other hand, out of control IT projects are a great way to milk stupid customers. Many IT businesses have built their empire on that kind of incompetence and billions of dollars still change hands annually for software projects that are over time, over budget and ultimately disappointing.
Jilles
Ajax and DOM, used with wddx is a good way to keep MVC model.
w ddx functions</a>, so having to communicate webpage with php very easy.
Soap can be used to extend the interface layer. Ajax calls to wddx objects are neat, and also php has <a href="http://www.php.net/manual/en/ref.wddx.php">
With javascript + dom control, you can process all the information you gather from ajax request to php.
I´ve working with ajax + php + wddx all day, since 1.5 months. I used to keep a MVC using a post to a Controller then a redirect to the next viewer if success or redirect to previus viewer with error flag at session.
Now I´m working with real mvc, the viewer only has the enough logic to display the info sent by wddx response. The controller is just an interface for set the values to call an object.
Very nice.
Â_Â
about sean dreilinger
The first is that you should focus on breaking the code into modules. A lot of people overlook that newer versions of PHP have lot of OO features that can ease development- though these people tend to not be pro developers. If you plan the site out and break the code into modules, aside from the other benefits, it can make it easier to keep a lot of the code out of the rest of the site, since you can largely just call objects.
The other way planning can come in helpful is to plan out the design with the designer. This way you can set up the code you generate to fit into the look and feel of the site without having to have someone who may not be familiar with PHP try to edit the generated HTML. If everything is planned out well, most layout changes can be handled by changing stylesheets without having to worrying about changing the underlying code.
One thing I've learned is that, sometimes it's simply not reasonable to not embed a content into your code. If you spend too much time trying to figgure out how to get around doing so, chances are that even if you succeed the resulting code will be at least a couple of: slow, bloated, buggy, obfuscated, or difficult to change later. Usually, if I have to generate a fair bit of HTML in my PHP, I do it like:
Usually, that way if someone has to change the layout later, they can skim through the code and see a block of mostly HTML that looks familiar enough that they can change it.
Famous Last Words: "hmm...wikipedia says it's edible"
The only way around having HTML in your PHP source code that I can think of is to create a class for making pages, with methods such as adding an HTML element and writing the page. The main advantages are that you can write new HTTP headers whenever you want without worrying that HTML was already output because you can write the class to only output at the very last moment, and you can rewrite the class to conform to new versions of X/HTML as they come out if you're cunning enough when you write it. But really, these are advantages of OOP with PHP5 just as much as they're advantages of taking HTML out of the main higher level source.
so for instance to get the title tag I would have something like.
Except that the function is part of a class wich does all the basic layout.
Why? Well I find it easier to maintain. But is this any easier then use doing
No not really. But what if the title is being generated from something else? What if the title isn't known until you reach the end of the code? Ofcourse there are other solutions to overcome this but this is the one I took.
There are a couple of forms of maintenance but basically if the designers wants to make minor color changes he doesn't need to touch the main code anymore, he can just edit the css file. IF he does want to make major changes to the layout I can far more easily rearrange stuff by simple altering the order of function calls then he can mess with template code or html with PHP included.
If I want to make functional changes I don't have to worry about having to wade through reams of html and find that I need to alter it completly. The code just looks cleaner to me.
In the end I can generate new function much faster by being in total control over the layout. What is easier displayField('user'); displayField('password'); or the html with all the php includes needed to set all the values to what you want?
Not everyone likes my method of doing things. Hell I seen people that didn't even use functions in PHP and they choke on my extended use of classes.
In the end I suppose the only real answer is to use the method that works for you.
Personally I never got the taste for using templates. Lots of reasons really but mostly because they are a pain to debug and for some reason template users never seem to bother with commenting their code.
Personal experience of course and I am sure other have different experiences but what else is there to judge things by but personal experience?
Basically, do what works for you if you are the one in control or use what your project leader tells you to do.
The first thing to learn as a developer is that there is no golden path to a succesfull project. Newbies often think that if only they use method X then everything will be alright. Nope, sorry.
The only method that works the tiniest bit is to at least be consistent. Try some stuff out and then settle on one method.
If you think that templates might be an intresting method go ahead and develop a test project with them to see if you like them and they make things easier for you.
MMO Quests are like orgasms:
You may solo them, I prefer them in a group.
Project Leader: Right you coder, the HTML designer doesn't understand PHP so you got use a template language instead you never heard off.
Coder: Oh okay, I can do that, so Designer guy, you can help with learning this template language?
Designer: No, I never heard of it either and I am going to just delete any html I don't regonise just like I do with php tags.
Coder: Fuck.
And this ain't a joke. My introduction to templates went pretty much like this. In order to deal with a designer who kept removing PHP because of the design program she used I had to learn a new "language" wich didn't help since she still kept deleting it.
Also templates are very limited if you want to do extra stuff. Like changing the layout of the table you just gave dynamically.
Is it possible to color each row an alternate color for instance? Probably it is but either way you end up adding more complexity to deal with what problem? Your designer unable to deal with your coding language? Get a better designer. Coders don't just delete html do they?
MMO Quests are like orgasms:
You may solo them, I prefer them in a group.
I seriously recommend you use XML/XSLT to render the html. In that way you can support markups in content and still have full control over the end result. And if everything is stored in a database its very easy to edit it through a lightweight backend.
Here is the main idea that helps me know when to dump html into my code:
When I am generating html dynamically, (nested tables, dynamic rowspan and colspans, converting a data structure into a specific view, keeping track of open-close tags, etc) I embed the html snippets into the code.
When I am displaying or presenting something (multiple rows, looping over elements) I have an html template, and embed php that echos out data elements.
In the end how does it boil down? About 98% of the html I write is in templates. I set up a standard data structure, then my templates echo the data out of those standard locations. It makes it easy to switch to XML, CSV, plain text, or whatever... Only about 2% of html I write is ever in a file stored as a string or something.
Out of all the reasons to do things this way, here is my favorite one:
A wise man once told me that the more lines of code you can see on the screen at once, the more productive you can be. So why clutter your code all up with HTML?
One thing to remember is *complete* seperation of data, presentation (style whatever) and code is never possible. Each are meaningless without some of the other. Seperation is a good practice wherever it's applied, but don't be fooled into becoming obsessed by it.
The thing is, sometimes dirty php hacks are fine.
What are you coding? If I went to ebay, or amazon, or something like that, and they didn't have a serious n-tier architecture, and all their logic code was scattered randomly throughout their html source, that would be a proper WTF.
On the other hand, when I knock up some sort of ultra-basic blog for myself, or a cheesy feedback form for my band's website, or something like that, then using full-on OOP and MVC is an equally big WTF. In that situation, please stop about impressing other people on slashdot with your architecture model professionalism, and write something shamelessly quick and easy. You're going to be the only person updating it, so who cares?
One further point on that subject... everyone praises a clean separation / MVC approach for being essential when you have multiple developers updating code. Well... true in a way... but there are qualifications to that. I remember doing some hacking on php blogging software Plog for a customer last year. That's completely OOP and MVC, using Smarty for templating, and the intellectual side of my brain was impressed with the cleanliness of the design patterns, but the practical side of my brain found it a pain in the arse. The client would say "you see this output of such-and-such a word on such-and-such a page, can we change it?" If it had been I'd go into the source for that page and it would be pretty much a single line of code...
model._request->("by_categories").view
or something ludricously cryptic like that. So I'd have to trying and "trace" things from the by_categories.php through the templates into all the object classes... of course the OOP was so fully-blown that you'd reach some initial completely generic class whcih told you nothing, you needed something which inherited off something which inherited off something.... etc, etc. It was an absolute nightmare, for the simple reason that the documentation, like so many OSS projects, was extremely lacking, verging on non-existent. I went to their wiki and found a page with the perfect title, something like "which functions are handled in which classes", but it just said "coming soon".
To their credit, when I asked on their forums I got a quick and friendly reply, but still, I think it illustrates my point. If you're going to put things into an elaborate architecture so that what-you-see-in-the-final-html-pages bears almost no direct relationship to organisation of the 'business logic' source files, then documentation is essential otherwise it's actually harder for multiple developers to hack than if you just stuff your html full of inline php.
After working on a project with various modules with various levels of bits of business logic and application logic in the content rendering areas, my coworker and I have decided on a new approach: the application will output XML, to be transformed with XSLT (server side or client side) to HTML, linking CSS. There are several advantages:
1) You have a simply defined interface between the application and display. Bonus points for making DTDs.
2) Most UI changes can be made in the CSS by somebody completely ignorant of the code.
3) The rest of the UI changes can be made in the XSLT by somebody completely ignorant of the code.
4) There is little temptation to put business logic in the display component. It is easy in PHP/Perl/JSP. To do it in the XSLT is almost always going to be harder than doing it right.
5) Add a set of XSLTs that output XSL:FO, add a XSL:FO processor, and you can output PDF or RTF with no application code changes.
6) XML is still a good buzzword. Managers love to say "Our product is XML enabled."
7) Its easier for other programs to interact with your program.
The disadvantages I believe are outweighed:
1) XSLTs are harder to write than JSP/PHP/Perl.
2) If you don't want your program to be slow, you have to generate your XML serially. This is harder than dumping data into variables and maps and referencing them from the content renderer.
The masses are the crack whores of religion.
A good web app has 3 layers: the code, the markup HTML (wireframe only), and the CSS. I strongly encourage you to check out CSS Zen Garden to gain insight to this powerful model.
For a serious web app, mixing logic and presentation is disaster. It becomes a huge headache to change even a simple thing in your presentation. Other developers that need to edit your code can't jump right in. They have to sift through all your crap, completely killing any of the supposed time-savings of building it hastily in the first place.
However the last layer, the CSS, is the most over looked. CSS has wide browser adoption now and is extremely powerful. There are numerous performance benefits for using minimal HTML and pushing things to CSS, mostly centering around CSS getting cached locally. But CSS also provides a tremendous amount of flexiblity for layout. You can drastically change the layout simply by changing the CSS.
More over, when built this way, you can let a much lower cost CSS specialist (pixel pusher) worry about how much padding there and what color widget there, and let us Web App Developers stick to the meat of the project. It's a great way to split the task up in a team environment.
I cannot over emphasize checking out CSS Zen Garden.For the small site I am working on now, I tend to write functions for logic that return data to other functions that then draw it. The main page includes these functions and is mostly html with a few includes and function calls. This keeps most of the application in seperate files than the layout logic. Ofcourse there is nothing wrong with using some logic in the layout functions to chnage the output based on th data, saves me rewriting code for every case.
Come as you are, do what you must, be who you will.
I would think your choice depends greatly on the taks at hand. Personally, when I create web applications I prefer to use the MachII framework which uses the MVC design pattern. However, they are commonly tasks given to me for which this is simply unnecessary if the "application" is very small or very static. I know many programmers are strongly against ever mixing your logic with your presentation, but I like to think my saved time is valuable too.
People seem much brighter once you light them on fire.
All of the presentation stuff should be done using CSS these days. The HTML should be purely descriptive of the content, not the presentation. Therefore, HTML is fine inside your PHP. CSS is not.
That, in my opinion, is where the line is drawn - between the HTML and the CSS.
There may be other benefits in some cases to removing HTML from certain PHP classes/functions, such as reusability.
Unless you have a very good reason for not doing so, always keep your presentation(HTML,RSS,whatever) seperate from your code.
There are several reasons for this:
1. It is much easier to edit HTML that actually looks like HTML, and code that actually looks like code. Debugging a 1500 line web page that is mixed code and HTML is my personal definition of hell.
2. If you are worried about designers screwing up a simple templating language just imagine what will happen when they start screwing up your inline PHP/ASP/Perl/Java code. i.e. "I removed all the weird looking stuff". Oops.
3. If you are using source control, it is handy to keep revisions of application logic seperate from revisions to look and feel. If something breaks you can quickly fingure out if it is a code or template problem based on revision history.
4. What is the downside? You need two tabs open in your editor? You need to learn a basic templating language?
Stupid sig of the week: Perl Hackers DIIMTOW
My designer keeps all her stuff neatly in the CSS. If she needs to do something in html, she writes the html and gives it to me, so I make sure my code generates that html.
We work on large websites and have our own heavy duty CMS, so there is no other choice than seperation of content, code and presentation. The code generates XML with all the right content taken from the CMS-controlled repository, a database or whatever we need, and only in the last step is all the xml turned into html by an xsl. If my designer wants different html, I change the xsl that generates it so she gets what she wants. The css is all hers.
"Well thought-out", eh? Hmmm... that's an interesting approach. Can you recommend a framework I can use to evaluate this "well thought-out" methodology or a consulting firm which can provide mentoring specialists?
Proud neuron in the Slashdot hivemind since 2002.
I know I know... it's not LAMP, but the lessons I've learned using ASP.NET and using code separation are: do it. Having done a lot of inline coding, I think code separation really works better in the long run. I also looked at Ruby on Rails, and I have to say that I am impressed with level of separation that it fosters in your code as well. If you separate it, it's easier to read and maintain later on when you haven't seen it in 6-12 months. I am still maintaining legacy ASP code and it's way harder to recall functionality because you have to trace through the page to figure out the behaviour. Stuff like separated ASP.NET or Ruby is much easier because you just look at the events or functions without any extra fluff padding your code.
Keep your code separate if at all possible. You or future others will thank you.
Okay I'm not a large web designer I have done a few small sites, nothing personalized, everybudy gets the same view of the data, no logins. So here is my method.
each page pulls in a header and footer and css in these files is only php and html, but no content, it is all pulled from a database. Usualy there is only a few lines of content that doesn't come from a database.
after those are pulled in the main part of the page may be html and content, but I'm moving away from having content in the pages as well, I've started making all content in a database, that my php functions pull out and display.
I can currently add an entire of page to a site with one line of sql adding it to the site directory, and uploading a small page usually only 1-2k of page and then uploading a database table with the actual content. No changes are needed to the header or footer so growing the site is painless.
I rarely have to edit my php files, and adding content to the site is usually just one sql insert statement. I also try to date/time stamp each new record so I can update the main page with When was the last content was added so people can see that the site is fresh and not neglected.
I also have a news page that just displays a list of entries about what I updated on the site so people can find the new content.
you can see this in action at
www.unixconsult.org/u20 and blastwave.org/smf
HTML should not ever be in your logic code, but you can have some logic in your PHP.
For that to work you need a genuine logic layer. Using an MVC pattern can help a lot, but all you really need is to use something like the Smarty template engine (http://smarty.php.net/). Smarty will give you a simple templating language, then in your logic layer you assign the needed values for the template to use.
In my current project I assign mostly arrays (like a DB resultset from ADODB's GetArray function), but there are a handful of objects and quite a few string or int variables. All of these variable assignments are done in the controller so they're not mixed throughout the site. So the controller invokes the classes that do the work (and pass in the parameters the classes need to work), then the controller takes the result data and assigns it to a template. You can do whatever you like to get the data, but just remember you don't ever need to use echo or print().
In the view layer (Smarty) the template will be HTML and simply drop variables where they're supposed to be. Eg: {$page_title}. The only logic in the template is the view logic such as iterating over an array or using a Smarty {if}..{else} statement to decide which piece of HTML to output.
The global economy is a great thing until you feel it locally.
Here is how it is implemented:
First the problem: The project is to import purchase orders, create a freight shipping request, price the request against an arbitrary number of trucking company rate tariffs, present the user with a list of rates, allow him to select the truck company, produce a PDF hardcopy bill of lading, and send the bill of lading via X12 EDI or SOAP to the truck company. Or alternately, the user can manually create the shipment request instead of importing a PO.
The solution is :
Smarty is great. I only have to pass it the variables. All the output is handled by the template. There is absolutely no presentation code or html in my PHP except for those few cases where I am outputing a preformated string as an AJAX response (and those I use sparsely). I could probably get away without formating that response and let the JS handler do it, but that would be more code than it is worth.
Separating presentation from content is always a good thing, and it's a requirement I had for my own website. I did a bit of research for ideas on how to do this in a web application, and the solutions that others have presented here (like the Smarty Template) and other template-style presentation mechanisms were the common solution.
One problem with this approache was mentioned in the Architecture Patterns book; depending on how your site is designed, you may have to edit multiple template files to change something in your website's presentation. For example, if you have a set of links that should appear on every page, you may have to change each template file to change something about those links.
So what I've done is separate the content from the presentation the same way I would have if my website was static HTML. The HTML is nothing more than data wrapped in DIVs, and my presentation information is completely contained in CSS files. I've also separated the presentation classes from the application logic in the script. The markup is still embedded within the script, but that script does nothing else than aggregate the data and the markup.
This way, I can put common data (like general navigation links and titles) in a class, and page specific content in sub-classes. If I want to change a link in all pages, it's one change. If I want to change the data in a page, it's just one change as well. If I want to change the look and feel, I do so in a single CSS file.
It's definitely overkill for a personal website (although another goal I had was to see if this could hold up as the website grew). So far, it seems to be holding up, even if I'm still fairly early in development.
Phemur
I typically embed HTML within my Perl CGI code in order to just get things done initially. The primary focus is on functionality, not aesthetics or maintainability. Once things are functional, it depends on how complex the application is and who will be using/managing it. If it's just a quick and dirty admin script to do a few basic tasks, I wouldn't even worry about it. However, if it is something that is likely to continue to grow and be maintained by many users, I will typically move the HTML out of the main codebase and create HTML template files that can be managed separately and are loaded by the CGI code. While it would be nice to develop all applications this way, often it is not necessary, and you'll never see the benefits of having done so. Then again, once you've created a template framework, it's not terribly difficult to reuse either...
If you really want to embed PHP into your HTML and want to cope those HTML monkeys happy it's worth knowing that the PHP interpreter understands this:
:( so your pages won't validate in their un-executed form, and PHP doesn't understand the type attribute.
<script language="php">
your code here
</script>
Unfortunately the language attribute is depreciated as of HTML 4.01
1) Avoid anything that will make you have reduntant copies of the same code, whether html or perl/php/java/whatever. That bring maintainablility through centralization of common things.
2) Avoid code that is doesn't look semantically related to the actual work you are doing. That brings maintainability by avoiding over-abstraction.
In this case, and in my interpretation, it means:
1) use a good templating engine that lets you have a single place for the structural <html><head><etc> tags, instead of repeating them in every page. I use a home-grown system called iAct, but you'd probably be better off with something more widespread.
2. Separate presentation and logic, because you'll probably at some point want to have different presentations for the same content generated by the same code, and that would mean duplication if you didn't keep them separate.
2.5. Separating presentation and logic doesn't necessarily mean all Perl/PHP goes on one side and all HTML on the other. For example, if you need to use alternately colored rows on a table, that's actually presentation, even if you might need a line of programming or two to achieve it.
3. Use ideas from MVC, but if you find yourself writing code that litterally looks like $object->preform_action(), stop and go back a step or two.
While there are many different ways to skin this cat, our workplace (and my previous one, and the one previous to that) uses an MVC approach utilizing the Spring framework, Sitemesh (to handle the header, navigation, and footer portions of the presentation) and Freemarker as the view technology.
This approach has worked incredibly well as it allows our rather large applications to be split up amongst several developers, each of whom have strengths in different areas (although each can code in any layer, be it presentation, business logic, web services, or data layers).
In essence, we use Spring based controllers to handle the GET/POST requests, build the model (which is then exposed to Freemarker), and pull in the presentation view (which is obviously Freemarker based).
Sitemesh is used as a filter to decorate the Freemarker-generated web pages (presentation) with headers/footers and whatever navigation is relevant on that particular page.
All in all, a very nice setup, with good separation of powers (ie., MVC).
-- Even racing cars don't crash as much as windows. --
The more the logic is separated from the code, the better.
I am an artist/designer with a bit of programming skill. I used to use Gallery as the backend for my site. Gallery 1.x spits out horrible, ugly table-based HTML. And this HTML is intimately entwined with its PHP code. I browbeat it into making reasonably clean HTML that I could style. It took a hell of a long time, because I had to dissect and understand a lot of its PHP code. I pretty much got a working knowledge of PHP doing this.
Then updates happened. I'd had to so extensively modify Gallery that merging my design with the updates was a bigger task than doing them from scratch was. And the 2.x strain of it, while it has a templating system, has a terrible case of second-system effect - it's huge.
I switched to Singapore. It was close to being my original choice, but it lacked a couple of features it's since added. I was able to exactly duplicate my design in a couple of days, because its templates are firmly separated from its logic. It would have taken even less time, but I took the opportunity to clean up my code a little.
Singapore just updated. I haven't updated my installation yet, but it's a task that actually seems possible.
egypt urnash minimal art.
My method for doing things... is to have markup in the code. Yes, it does involve changing the code when the overall design gets finalised, but then it stays changed.
before people think 'eeeww' let me explain.
Everything goes through a common file... index.php
functions that are common to all pages are kept in a 'common.php' file (strange that naming convention!)
I use a "Page Switch" array (keys are the 'page keys', values contain the file to require and the function in that file to call to generate the page content)
eg... for the URI index.php?page=list_productsThe page content function will generate the code for the page (if you really wanted to seperate the code and the markup, it is quite possible to do so in the page content function)
I then use another function to send the page to the user... this function wraps the page content in the sites theme and away it goes.
There a both benefits and drawbacks to this system, Most of the benefits are in the developing/maintaining side of things... you can change 1 thing and it changes everything across the site (which can be disasterous as well)
As for performance penalties... these can be turned around by using something like the Zend Platform (if Zend still call it that). It precompiles all the scripts your site needs to run, so here - having fewer scripts running becomes a benefit!
If you are not running any funky performance increasing tools, you just have to watch what goes into the common file.
I also make use of some OO, but only when it makes sense, and in moderation (3GL programming still has a purpose!)
But, I suppose, the most important thing to remember, Design the program for what its purpose is. There is no use wasting time over designing something and there is equally no use doing a quick hack when something more robust is required.
Do it once, and do it properly!
A Tale of 2 idle hands
..better still would be to include_once() a function that did anything 'one notch' or more complicated from that, I think anyway. I agree 100% it is it's own templating language, but I still wouldn't feel comfortable putting naked loops in my HTML. On other hand Smarty is overkill to me. I usually use a structure whereby there is the HTML tier (which have as few include_once's as I can get away with), and then a tier where PHP and HTML collide in the form of UI functions, and then at the top is pure PHP tier, usually concerned with abstracted database access and the like. I hope I don't look stupid.
Take a look at Catalyst at http://www.catalyst.perl.org/ it is MVC with a lot of options and very nice to use...
hmm that rimed sort of.. anyway, the model view controller approach works well. My HTML pages are mostly just that. I'm using Java so the HTML becomes struts tags, as well as custom tags. My feeling is that I want my JSP to be more HTML like than anything else. Where necessary I use JSP, but more often I use javascript instead. This means that someone who knows HTML and JavaScript can do a page up. They do not need to be super smart in JSP. The controller is all done in servlets. They process the forms and then forward to other controller servlets or do business logic and then forward output to JSP page. The JSP pages have custom tag libs, that cna then display the results. The struts framework allows me to output error messages by putting a tag . There is also the ability to put that tag with an attribute for a field name and place on specific places on a page. Also it is possible to make all these error messags javascript popups pretty easily. This level of seraration is not so important when developing a site like slashdot, where they get to say what it looks like. However when developing a site that needs to be cusomtized per client, it is extreemely important. This is what I am working on. So one client uses our web front end to do their business and the site is customized for them, and another does it differently and it is customized for them. The customization is done by someone who understands HTML, JavaScript and a little JSP and XML. Really simple to customize, but very flexable. This has worked really well.
Only 'flamers' flame!
Does slashdot hate my posts?
I keep application logic seperate from presentation logic. If you need to create a table based on dynamic content, you will need code in your html to do so. This should be kept seperate from program logic where, for example, a database query might take place. The result set can be passed on to the template where the presentation logic takes place.
I've found a very effective way of doing this. I have a template object that stores template variables passed to it. When you are ready to generate the html, you call an output function which that takes the variables passed to the template object and imports them into the current namespace, and then reads in the template file and interprets it natively. Using output buffering, you can save the resulting output.
Ultimatly, it makes reading the code itself a lot easier, which in turn leads to better productivity, collaberation and debugging.
As a side note, I was looking through the code of an ajax framework today, which claimed ease of use since you only needed to include one file into your code to make it work. Taking a look through it, it was a mess of html, javascript, php and css. No thanks.
Similes are like metaphors
Hmm, this post is giving me some troubling thoughts about how I've designed my site.
I made it in this sequence:
- Made a complete HTML/CSS layout
- Made individual PHP pages to grab database stuff and output it in HTML
- Broke the layout into two files at the "content here" part
- Included file 1 as header.php and file 2 as footer.php in the appropriate place in each PHP file.
Later I realised this didn't allow me to customise the title attribute so I had to go back and split header.php again to allow me to define this in the php files after the queries (dynamic titles).
Now I end up with a ton of php files all doing similar stuff for a database frontend (eg, add feature_x, delete feature_x, edit feature_x, list feature_x etc) all full of html and stuff. It's messy and needs some improvement - any tips?
Matt
my process is pretty simple... but not optimal yet.
1. i have a php page for the logic code.
it submits to itself and forks to a processin code path if submitted.
this submitted code path will then do its work and include or redirect as required.
2. i have templates to display the data. i started out with a single template for each logic page - and a few include files for headers, navigation and footer. in order to DRY (don't repeat yourself), i've started taking this to the next level where i have a master template and then i include only that data that changes. all the layout code is in a single place.
if i get an error connecting to the db, i'll set a variable and call the template. the template checks for the variable and displays the variable error message.
if i don't get an error and the form data is entered or the query succeeded, i use header to reload the page. if i need to send info to the reloaded page, i use a session variable.
i do include some php code within my templates, but the code is *display* code, not general logic code. display code is on the display page - right where it should be!
anyway, it isn't perfect. i'm always trying to clean it up in order to make it more efficient (readable, debuggable, DRYable, etc...).
i would recommend using a forms class and a db abstraction layer. i use manuel lemos' forms generation and validation class (phpclasses.org) anf adodb's db abstraction layer. i'm very happy with both - they've dramatically improved functionality i can put in my apps - especially the forms class.
3. keep improving the code... DRY, work out rational organization conventions, separate logic, display and content... it is a process and continuous improvement is the way to go.
OK. I know this is gonna be controversial. But isn't the whole point of separating HTML from CSS about separating style from content?
Done right, the XHTML page is just a hierarchical data-structure. It's rightly part of the program and so part of the programmer's domain. CSS gives you all the control you need over the *appearance* of the page.
So I say the designers shouldn't mess with anything except style-sheets. No PHP, no HTML templates, nothing but CSS.
Of course, although XHTML and Javascript are part of your program, they're a special part of the code which gets executed in the browser. By all means you should also have a good strategy for encapsulating them away from the rest of your code. Have some kind of templating system if you like.
But it's a mistake to think this is the *same* separation as the firewall you want to put between coders and designers.
The problem is, of course, the *tools* aren't set up for this. Dreamweaver et al. imagine that the designer will be creating the actual HTML. I'm not sure if there are tools that support the separation I'm suggesting (but you know, toolbuilders, there should be) but it seems to me crazy that we're trying to invent and police the firewall between coders and designers when it already exists.
As for code and "content" if you mean the text and images on your site, these should probably be in a database or CMS of some kind rather than embedded directly into the HTML.
Easy.
For me, it is clear anyway.
Java is code, XSLT is the Layout and XML is the content.
Furthermore, when you combine relationally, XML and XSLT code embedded into SQL databases, you have the ability to add security to your servers, that is not attainable otherwise.
The reason, is that nothing is ever stored as a HTML file, or a file on the web server.
Everything is a URL that translates into a SQL table to get XML or XSLT code to layout content.
Thats right, to update your website you just talk to a bunch of SQL tables and that is all. You do not give a login to your web server, or your app server to people. Just the SQL server.
I am working with my current employer to see if he would let me release the framework as an open source project, because it is MUCH better than the LAMP model or PHP crapola that requires you to put HTML all over the place in files that clutter and make securing 3 or 4 different servers from users who want to update content, to programmers and what not.
-Hack
Got Geometrodynamics? Awe, too hard to figure out? Too bad.
you don't seperate code from markup, you seperate different types of logic.
eg:
<?php foreach ($customers as $c): ?>
<tr>
<td>
<?=$c['id'];?>
</td>
<td>
<?=$c['name'];?>
</td>
</tr>
<?php endforeach; ?>
But then, in another part of your code, you generate the $customers array from a database, and shove that array into your template.
To speed things up, you can use a database that supports views like MySQL 5 or SQL Server (does PosGreSQL support views? think it does and it is open source). Also, you can cache the templates and simply clear the cache or rebuild the template every time the contents of a view have changed.
Using proper HTML and CSS can make things even easier. As someone else pointed out in this discussion, with the right skills, you can setup your site to be completely CSS driven, and simply adjust CSS files as necessary.
your templates shouldn't contain much logic other than rudementary iterations and echoing of variables.
It's been my experience that Perl sucks at this and PHP excels. I've never tried ruby so I can't say, but lots of people seem to swear by it.
I'm god, but it's a bit of a drag really...
Keeping content, presentation and logic seperate is fairly simple until you move into more complex data presentation where the page presentation itself relies upon the data.
For example, depending on the status of an item in your database you might need to print a form on the users screen if it's in one state, but if it's in another state you just want to print out a simple string to say so.
In cases like that you either have to embed a chunk of presentation and content into the code directly, or create some messy template snippets which in my experience aren't much more legible than just embedding it straight into the code. Both methods remove any chance of passing the design to a non-technical person, also.
So in summary, templating is a good idea, but it has limitations and is not the panacea of web design abstraction.
I run into so many people (on slashdot) that don't get design that I have to mention this. For the best DESIGN, content and design need to be completely integrated, not separated. A magazine page does not separate the text from the design. It IS the design. (Which makes designing for the web a real chore.)
What needs to be separated is the CODE. But remember, designers need (in their world) graphic control of everything. Essentially if you want to code for designers (common in web programming), the rule of thumb should be, 'can the designer DESIGN my code'. If you can separate the code and still allow the designer to control how it looks in all situations, then get it out of there... But if you can't, you should leave it in.
Web designers are not the MOST technical people in the world, but they're not weaving baskets either... they can certainly figure out what is PHP and what is HTML. Don't be afraid to leave some code in there if it gives the designers more control because this will ultimately make the site more usable to your end user which is probably the ultimate goal in the first place.
Here is my two cents.
CSS is there to help you.
Make a full use of CSS.
Use simple html elements with no color, border or any display related properties. Declare them with the proper style. If you don't know the difference between class and ID. I strongly suggest you to by a book about CSS.
If you have carefully design your stylesheet you will be able to fully manage the display through a CSS file. Things are really more simple that way.
Don't be too "extremist"...There are a lot of cases where a good old table is better than cascading DIV tags.
Too many developers are still using the old way (only HTML tags), or a part (text formatting) of CSS. Simply by a book about CSS you will be astonished by its power. People complain about IE CSS support...But there are already enough supported things to be fully part of your solution.
From a discussion on BayPiggies about MVC:
Someone wrote: "a lot of the related literature seems to use MVC as the canonical example of a design pattern"
MVC is the canonical example of the "Cargo Cult" design pattern of blindly aping Smalltalk without understanding it or considering if there are any more appropriate design patterns.
http://en.wikipedia.org/wiki/Cargo_cult
I've never heard a good explanation of what a "controller" is really supposed to do (other than entangle brittle dependencies between the view and the model, and allow programmers to bill for more hours maintaining the code). But people always throw in that extra "controller" class and its requisite complexity, just because Smalltalk uses them, and it doesn't feel right imitating Smalltalk without the whole MVC trifecta.
Just because MVC is a commonly used and cited "pattern" doesn't mean it's the best one to use in all cases. It's better to have a "purpose" than a "pattern".
http://osteele.com/archives/2003/08/rethinking-mvc
-Don
If all the messages between the model and the view have to go through the controller, then it sounds like a bunch of middleware glue to me. Maybe somebody should write a SWIG-like tool that automatically writes all your controllers for you, since it sounds like a horrible mess to have to write and maintain by hand. I prefer the KISS approach of not using controllers at all. Given any piece of software, there's always going to be a bunch of miscellaneous functionality and glue code that doesn't fit into the nice little boxes envisioned by the designers. With MVC cargo-cult designs, all that miscellaneous stuff gets thrown into the "Controller" class, so it's more appropriately called "Model/View/Etcetera".
MVC was originally designed for Smalltalk, which is a dynamic language with closures, so it just doesn't work as well with static languages like Java (which eventually had to fake closures with inner classes). Java programmers end up abusing controllers to make up for deficiencies in the language that aren't such a big deal in other languages (like dynamically dispatching named events to methods, persistence, scripting, and customizing methods and properties of individual objects, etc). They end up re-inventing little pieces of other languages like Smalltalk, Lisp and Python, and the poor Controller (Etcetera) ends up being where they dump all that glue code that would otherwise be built into the programming language and framework.
-Don
Smalltalk was successful for the same reason the Lisp Machines (including MIT's CADR, Symbolics' Genera, TI's Exploder, Xerox's Interlisp-D) were successful: they had a rich, wonderful, interactive programming environments, which supported exploratory programming, and let you examine, modify and debug the entire state of the system, from the user interface all the way down to the file system and networking. Smalltalk was also successful in that it inspired and influenced a lot of other important languages like Self, which led to the Java hotspot compiler: http://research.sun.com/features/tenyears/volcd/pa pers/ungar.htm
The Eclipse platform was heavily influenced by IBM's extensive work on Smalltalk, and it shows. Sun's doing themselves a lot of self-inflicted damage by boycotting Eclipse, not because it sucks or they have anything that can touch it, but simply because they can't take the joke about its name. (But that's how IBM planned it -- who said a big blue corporation couldn't have a sense of humor?)
More on the "Cargo Cult" design pattern: http://www.softpanorama.org/SE/anti_oo.shtml
-Don
The complexity comes from King Solomon's solution of dissecting the input ha
Take a look and feel free: http://www.PieMenu.com