Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

why use OO nature in CGI?

by sulfericacid (Deacon)
on May 21, 2005 at 06:18 UTC ( [id://459197]=perlquestion: print w/replies, xml ) Need Help??

sulfericacid has asked for the wisdom of the Perl Monks concerning the following question:

Probably a question just as old as CGI itself but why would someone go through the extra TROUBLE in using the OO aspect of CGI instead of just hard coding the HTML manually using heredocs?
print scrolling_list('list_name', ['eenie','meenie','minie','moe'], ['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}}); -or- print scrolling_list('list_name', ['eenie','meenie','minie','moe'], ['eenie','moe'],5,'true', \%labels,%attributes); -or- print scrolling_list(-name=>'list_name', -values=>['eenie','meenie','minie','mo +e'], -default=>['eenie','moe'], -size=>5, -multiple=>'true', -labels=>\%labels, -attributes=>\%attributes);
That to me looks like you have a better chance of making a few typos or syntax errors as opposed to the alternative. When I started learning HTML I NEVER went the OO route and any time I download free CGI scripts to see how things were done, it's actually a rarity that they are using it.

They all seem to be doing it the "easier" way. I heard objects make a script or program more portable but in terms of a CGI email contact form, when wouldn't typing out the HTML be portable enough?

There must be something I'm missing. For you CGIers out there, which method do you use? Why?



"Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

sulfericacid

Replies are listed 'Best First'.
Re: why use OO nature in CGI?
by jhourcle (Prior) on May 21, 2005 at 07:27 UTC

    Well, I think this is actually two questions -- why use CGI to dynamically generate HTML, rather than hard coding your HTML, and second, why use the OO interface to CGI, rather than the function calls.

    The OO implementation ismay be faster than the function calls. So, that answers #2. (but you're not using the OO syntax, so let's get to the other part).

    Now for the question, why use functions to create everything? I don't know for everyone, but I think part of it is a historical thing -- there was a time when HTML was in flux, and new versions were coming out. The big problem, with the change from HTML 3.2 to HTML 4.0 was that a bunch of tags were deprecated. (which is why there's 4.0 transitional, and 4.0 strict) If you have the extra layer of encapsulation, you can do checking, to make sure that the values are valid, and that you're not using tags that you're not supposed to.

    You also have the advantage that Perl will generate syntax errors if you don't have matching parenthesis, rather than needing to check the HTML afterwards. (well, it's still a good idea to validate your HTML).

    There is also the advantage that you can remove highly repetitive tasks. Some of the potentially most annoying bits in generating HTML are the putting in selected/checked attributes on form inputs. (loop through, find right item(s), and add the extra code).

    So yes, there are times when there are advantages to not hard coding your HTML... but well, I tend to go the hard coded route. It's the way I learned to do things, I prefer having the extra control of exactly what gets sent. I keep meaning to learn some of the various templating modules, but I've never had the downtime to mess with them. (and it'd require the other 3 programmers on the project to learn it as well)

    Some people have problems with update inconsistencies when maintaining hard coded HTML (making sure that all of the items in a list are similarly modified), but CSS makes things easier, as do text editors with good find/replace functions.

    As for the 'free' scripts, well, some of those have been around since the days of Perl 4... they're not exactly things to strive for. (A few 'popular' ones in particular come to mind... *cough* formmail *cough*) Many times, they're written by someone who's just starting to code, and may not know the best practices, especially because they're trying to make it generic enough for anyone to use.

    update: 'is faster' didn't go with the rest of the comments about benchmarking... see below

            The OO implementation is faster than the function calls.
      That sounds counter intuitive, can you elaborate? Thanks.

        Oops...gotta hate when the top of your message directly conflicts with the bottom of the message.

        I should have said 'may be faster' not 'is faster'. The OO style is less memory intensive. In some situations, especially under mod_perl, the difference can be noticable.

        There is also, as mentioned in the CGI CGI docs, a little bit of overhead when importing the functions into your namespace that will most likely be more apparent when running shorter scripts.

        So basically, although the individual method/function calls may be a little bit slower under OO, the overhead it initialization may strip you of that speed.

        Of course, this goes back to the problem of benchmarks -- someone else's tests may not be representative of your situation, so if you're worried about it, you'd want to run your own tests.

Re: why use OO nature in CGI?
by bart (Canon) on May 21, 2005 at 09:47 UTC
    why would someone go through the extra TROUBLE in using the OO aspect of CGI instead of just hard coding the HTML manually using heredocs?
    You mean HTML tag generation by functions/methods, instead of by embedded literal HTML? Oh, some reasons:
    • Proper tag nesting is enforced by the nature of scripts
    • Easing automatic generation of some HTML, like the choices in dropdown boxes, and automatic escaping of entered values
    • Sticky values, i.e. when generating similar HTML again from the form input, values get automatically filled in with the old values. This eases error processing: the programmer doesn't need to do anything extra, while the user gets the old values he typed in last time back, so he doesn't have to start all over from scratch.

    To me, the latter point would be its major selling point, thought enforcement of proper tag nesting is a good second.

      You mean HTML tag generation by functions/methods, instead of by embedded literal HTML?
      There's actually a third option that I prefer for HTML forms in particular: mutable widget objects that serialize to HTML (or XHTML) on request. The memory overhead of this approach is slightly higher than HTML-generator functions, but this is far outweighed by the increased flexibility and, most importantly, potential for reuse. Fields with input and output filters, auto-inflate/deflate of values, compound fields (single "logical" fields made up of multiple "physical" HTML fields), etc., all make dealing with large, complex forms so much easier, IME.
Re: why use OO nature in CGI?
by cLive ;-) (Prior) on May 21, 2005 at 06:56 UTC

    The most common reason for me is modules. Let's say I have a script that uses a module I've written, and that module uses CGI (for whatever reasons). And let's say I want to use a second module that also uses CGI. There are several situations where, if both are using params sent via post that you will get burnt, because the content buffer only gets read once when creating the first CGI object.

    So I have a method in a common module like this:

    sub new_CGI { defined $Module::CGI or $Module::CGI = CGI->new(); return $Module::CGI; }

    and in each module, I just call the new_CGI method:

    my $q = Module::new_CGI;

    I actually use OO for this in RL something like this (very stripped down), passing the common module as an argument:

    use Module; use ModB; use ModC; my $m = Module->new(); my $mb = ModB->new($m); my $mc = ModC->new($m);

    I also use the common module to throw database handles around too. It took me forever to work out this problem initially, but now I find it a very tidy way to use modules already used.

    cLive ;-)

Re: why use OO nature in CGI?
by blue_cowdawg (Monsignor) on May 21, 2005 at 12:20 UTC
        There must be something I'm missing. For you CGIers out there, which method do you use? Why?

    Personally I don't (much) use the HTML functions in CGI myself. I would rather use HTML::Template and associated templates for all the presentation layer stuff and keep my code readable.

Re: why use OO nature in CGI?
by elwarren (Priest) on May 21, 2005 at 21:17 UTC
    When working in an environment where you're moving alot of data (probably in and out of a database) and you can't have it hardcoded in html, this does the job better and also allows someone else to maintain it:
    print scrolling_list(-name=>'list_name', -values=>@listdata, -default=>@listdefaults, -size=>$listsize, -multiple=>'true', -labels=>\%labels, -attributes=>\%attributes);
Re: why use OO nature in CGI?
by johnnywang (Priest) on May 21, 2005 at 08:39 UTC
    I'd say it's because of historic reasons, probably few people use it now. I venture to assume that most people now don't even hardcode html using heredocs, they use template systems: HTML::Template, Template::Toolkit, etc.
Re: why use OO nature in CGI?
by djohnston (Monk) on May 21, 2005 at 17:12 UTC
    In the end I think it's simply a matter of opinion. You could have two people look at two approaches to a problem: one might find one solution confusing but the other solution intuitive; the other person might find the other person's opinion backwards. This leads us to the old saying, "Opinions are like buttholes: everyone's got one, and everyone thinks that everyone else's stinks".

    Personally, I lean toward the templating approach - not because I think it is better than the other techniques, but just because it fits well within my manner of thinking. A friend of mine uses the same templating system (we've been working on it together for some time) but he also uses some home-brew CGI-like directives within his templates to generate the HTML (Warning: only a complete lunatic (or a genius) would dare combine the two). The advantage? He decided last week to convert all his pages to XHTML - all he had to do was modify his directive set. Done.

Re: why use OO nature in CGI?
by kwaping (Priest) on May 21, 2005 at 16:17 UTC
    In these days of WYSIWYG editors, it's possible they don't even know HTML. But the real answer is probably one of bart's items listed above. :)
      Howdy!

      A "WYSIWYG HTML editor" is an oxymoron, or selling a lie.

      It depends critically on assumptions about the end-user's browsing environment that cannot be relied on, under most circumstances. I'll accept a watered down claim that an HTML editor can display the marked up document in a browser-like setting, giving you a sense of what it might look like to the user.

      yours,
      Michael

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://459197]
Approved by kvale
Front-paged by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-04-26 00:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found