SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 35

Thread: coding standard

  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2007
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    coding standard

    Hi
    I want to get some expert comments about following two php snippets
    first snippet
    <?php
    for( )
    {
    ?>

    <html code>
    <?php
    }//loop ends
    ?>

    second snippet
    <?php
    for( )
    echo "<html code>";
    }//loop ends
    ?>

  2. #2
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    I would rather see something like this:
    PHP Code:
    <?php

    $format 
    '<tag>%s</tag><tag>%s</tag>';

    for () {
        
    printf($format$argA$argB);
    }

    # No closing ?-> oh noes!
    #Comment bug
    But that is just me.
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.


  3. #3
    SitePoint Wizard Mike Borozdin's Avatar
    Join Date
    Oct 2002
    Location
    Edinburgh, UK
    Posts
    1,743
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would use:
    PHP Code:
    <?php
    for(/*...*/):
    ?>
        <!-- HTML code -->
    <?php
    endfor;
    ?>

  4. #4
    Keep it simple, stupid! bokehman's Avatar
    Join Date
    Jul 2005
    Posts
    1,935
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by saqib ku View Post
    Hi
    I want to get some expert comments about following two php snippets
    first snippet
    <?php
    for( )
    {
    ?>

    <html code>
    <?php
    }//loop ends
    ?>

    second snippet
    <?php
    for( )
    echo "<html code>";
    }//loop ends
    ?>
    Have you got a question? If so please make clear what it is.

  5. #5
    SitePoint Addict
    Join Date
    Apr 2005
    Posts
    287
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    why not use heredoc


    PHP Code:
    <?php
    for( )
    {

    echo <<<eof
    <tag>hey</tag>
    eof;

    }
    How does that make your feel?

  6. #6
    SitePoint Addict
    Join Date
    Oct 2006
    Posts
    210
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    My style is to put business logic at the top of the PHP file. Either by using include/require statements or by using code directly. Then the bottom of the file is presentation logic. In most cases, this is HTML which escapes to PHP when needed. This allows me to read the HTML source code and get a better feel of the page layout. Another advantage is that I can see the page layout in a WYSIWYG editor (should I want to do that).

    Just my $0.02...
    mikem

  7. #7
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hey everyone.

    I gotta agree with Logic Earth here. If you keep a string as the format, it's faster, more efficient (and it looks better), if you use printf (or even sprintf if you want to store it).

    Why would you use HereDoc? It's much easier just to escape quotes - and it somehow looks cleaner to me if you use quotes around it.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  8. #8
    SitePoint Wizard Hammer65's Avatar
    Join Date
    Nov 2004
    Location
    Lincoln Nebraska
    Posts
    1,161
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arkinstall View Post
    Hey everyone.

    I gotta agree with Logic Earth here. If you keep a string as the format, it's faster, more efficient (and it looks better), if you use printf (or even sprintf if you want to store it).

    Why would you use HereDoc? It's much easier just to escape quotes - and it somehow looks cleaner to me if you use quotes around it.
    heredoc is great for very long HTML sections and SQL queries. The examples given I assume were short because they were just examples.

    I would agree with idea of putting code at the top and then echoing what you need in the HTML below. I find it makes it much easier to troubleshoot and maintain the code that way, if you aren't going to be using templates or more complex OOP structure.

  9. #9
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,784
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    The best way is to separate it into two layers - one for the HTML and another for the PHP that converts it into the web page. Makes things much easier for when you want to reorganise the HTML.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  10. #10
    SitePoint Addict
    Join Date
    Apr 2005
    Posts
    287
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arkinstall View Post
    Hey everyone.

    I gotta agree with Logic Earth here. If you keep a string as the format, it's faster, more efficient (and it looks better), if you use printf (or even sprintf if you want to store it).

    Why would you use HereDoc? It's much easier just to escape quotes - and it somehow looks cleaner to me if you use quotes around it.
    Well I assumed he wanted alot of HTML text... Could go either way.
    How does that make your feel?

  11. #11
    Resident Code Monkey Chris Corbyn's Avatar
    Join Date
    Nov 2005
    Location
    Melbourne, Australia
    Posts
    713
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I go with Mike Borozdin's version. The syntax used there is PHP's specific template syntax and is exactly what it's meant for. Separating PHP from HTML is completely pointless IMHO. Separating business logic from view logic is a different story however.

  12. #12
    SitePoint Addict whydna's Avatar
    Join Date
    Jun 2006
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Does anyone have an example where PHP is computed before the HTML? Perhaps a sample code for an entire page?

    Thanks!

  13. #13
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Thumbs up

    Does anyone have an example where PHP is computed before the HTML? Perhaps a sample code for an entire page?
    Sure. Say you have 3 queries for a basic front-page. These are to:
    1. Fetch the Menu for the site
    2. Get the content
    3. Add view count to the site

    (p.s. I know 3 queries just for this might be unefficient - its an example )
    Ok, so what most people would do is this:
    PHP Code:
    <?
    mysql_query
    ("UPDATE `stats` SET value = value+1 WHERE field='views'");
    ?><html>
    <body>
    <div id="main">
    <ul id="menu">
    <?
    $menuQuery 
    mysql_query("SELECT * FROM `menu`");
    while(
    $row mysql_fetch_array($menuQuery)){
       
    printf("<li><a href=\"%s\" alt=\"%s\">%s</a></li>"$row['url'], $row['title'], $row['text']);
    }
    ?>
    </ul>
    <div id="content">
    <?
    $contentQuery 
    mysql_query("SELECT `content` FROM `content` WHERE `page` = 'Home'");
    echo 
    mysql_query($contentQuery0);
    ?>
    </div>
    </div>
    </body>
    </html>
    It can be better structured in multiple ways, such as putting the PHP at the top:
    PHP Code:
    <?
    mysql_query
    ("UPDATE `stats` SET value = value+1 WHERE field='views'");
    $menuQuery mysql_query("SELECT * FROM `menu`");
    $contentQuery mysql_query("SELECT `content` FROM `content` WHERE `page` = 'Home'");
    $menu "";
    while(
    $row mysql_fetch_array($menuQuery)){
       
    $menu .= sprintf("\n<li><a href=\"%s\" alt=\"%s\">%s</a></li>"$row['url'], $row['title'], $row['text']);
    }
    $content mysql_query($contentQuery0);
    ?>
    <html>
    <body>
    <div id="main">
    <ul id="menu">
    <? echo $menu?>
    </ul>
    <div id="content">
    <? echo $content?>
    </div>
    </div>
    </body>
    </html>
    There are many other ways, for example keeping all the repeditive code in a top file, stuff like that.

    Hope that helps.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  14. #14
    SitePoint Addict whydna's Avatar
    Join Date
    Jun 2006
    Posts
    258
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It does thank you. I want to make the switch over to this coding style, but the pages I work with are much more complex and trying to imagine how it will handle.

    For example a page with:
    - navigation menu at the top
    - login//user info on the left
    - list of new topics on the right
    - query and play a video on the middle
    - list a bunch of user comments on the video
    - fetch random site news on under the comments

    Are we to store all of this content into PHP strings at the top of the page? I imagine it will become hard to follow if there are 2 variables initiated at the top and then try to follow them down the page...

  15. #15
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    nope - this is where OOP comes in.

    I use the factory design pattern, which is exceptionally handy when it comes to modules, etc. Maybe you want to check it out:
    http://www.sitepoint.com/forums/show...7&postcount=10

    That's what I use for the back-end of my site, and it means whenever I change design, I just change template.html and style.css - and it, just works.

    The way I do it means it's easily expandable. Heck, i've reused that code twice and all I need to do is create a design, link it to that, add menu items and I'm done. If I want to expand, it's easily done, I'm now even creating a blog add-on for it, and I've already made a portfolio extention.

    Apart from being able to expand it, it's also much easier to read, it separates files, and it's also benchmarked faster than procedural coding (on PHP 5).
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  16. #16
    SitePoint Addict Hero Doug's Avatar
    Join Date
    Nov 2003
    Posts
    250
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You know of all the solutions presented so far they generally require HTML in the business logic, or PHP in the presentation logic. That would limit the developer to using the output from the business logic (easily syllable I know), or going into the business logic and changing the output.

    If you want to increase the complexity a bit you could have the developer send a function the HTML to use in the loop so neither person need's the other to do their job, and the designer has full control over presentation.

    In your business logic function:

    PHP Code:
    <?php

    // The function to be called from the view
    function showMembers$html$pmUsername$pmBlurb ) {
        
        
    // Create an array for the place markers
        
    $placeMarkers = array( $pmUsername$pmBlurb );

        
    // Your loop (which you'll need to set up according to your needs)
        
    for ( $i 0$i 5$i ++ ) {
            
            
    /*  It's assumed that you'll get the required information in the loop (maybe a database
            *   query, or looping through a file, etc.
            *
            *   Just note that the replace works based on position, so make sure
            *   you add the info in both arrays in the same order.
            */
            
    $input = array( "Average Joe" $i"This is a blurb" $i );
            
            
    // Show the formatted info
            
    echo str_replace$placeMarkers$input$html );
            
        }
        
    }

    ?>
    And in your presentation logic
    PHP Code:
    <h1>Members Demo</h1>
    <?php showMembers"<tr><td colspan='2'><hr /></td></tr>
            <tr><td>{username}</td><td>&nbsp;&nbsp;</td><td>{blurb}</td></tr>"
    "{username}""{blurb}" ); ?>
    Granted it's a bit of a big function call, but it keeps the design elements in the designers hands and formats the info.

  17. #17
    SitePoint Addict Hero Doug's Avatar
    Join Date
    Nov 2003
    Posts
    250
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just a note on usage : I used the example of member info to illustrate a possible scenario in which you may need to use a loop to display data.

    in the function to call the formatted data from the loop there are at least two arguments: the markup, and one or more place markers (which are used to identify the location to insert data)

    If your loop needs more information just add more placemarkers to the placemarker array and another argument to the function signature for each additional placemarker.

    It should be easy for you to customize.

    P.S. Also, to give you a direct answer about your origional question: both methods do exactly the same thing with one minor difference.

    The first way won't show any PHP in the HTML output, and you don't need to worry about escaping strings. You can put most anything in there wihtout affecting the PHP script.

    The second way will echo the HTML as if it were a PHP string. So that means it may also echo a variable should you have one in your HTML. It may also cause an error if your HTML has the same quotes as your string, so you have to escape them (just note that the function I posted suffers from these drawbacks).

    Overall I'd say the first way is less work if you're planning to mix your HTML and PHP.

  18. #18
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I also do as Mike B does in template files. The colon and endforeach/endif/etc syntax makes things clearer when mixed with HTML than curly braces. A separate templating language just wastes time.

  19. #19
    Keep it simple, stupid! bokehman's Avatar
    Join Date
    Jul 2005
    Posts
    1,935
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The crap thing with having HTML sections in your code is that the HTML section is echoed automatically rather than returned.

  20. #20
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Exactly - which is why I store output HTML in files.

    In fact, a maybe better approach would be to store all the HTML modules you use in a database, which would completely save the need for any HTML in business logic. (I think).

    For example, if you had a simple shopping cart, you could have the following rows in the table to show it:
    CartHeader
    Code html:
    <table>
    <tr><th>Product Code</th><th>Item Description</th><th>Price</th></tr>
    CartRow
    Code html:
    <tr><td>%1$s</td><td>%2$s</td><td>£%3$s</td></tr>
    CartFooter
    Code html:
    </table>
    (Maybe that's a bit of a long-winded approach - it's an example )

    Then you could use the following:
    PHP Code:
    <?
    $getHtml_Top 
    mysql_query("SELECT html_output FROM html WHERE name='CartHeader'");
    $getHtml_Row mysql_query("SELECT html_output FROM html WHERE name='CartRow'");
    $getHtml_Bottom mysql_query("SELECT html_output FROM html WHERE name='CartFooter'");
    $top mysql_result($getHtml_Top0);
    $row mysql_result($getHtml_Row0);
    $bottom mysql_result($getHtml_Bottom);
    echo 
    $top;
    foreach(
    $_SESSION['cart'] AS $item){
       
    printf($row$itemgetDescription($item), getPrice($item));
    }
    echo 
    $bottom;
    it was a bad example, but if your that desperate to separate logic from HTML, it works.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  21. #21
    SitePoint Addict Hero Doug's Avatar
    Join Date
    Nov 2003
    Posts
    250
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I also do as Mike B does in template files. The colon and endforeach/endif/etc syntax makes things clearer when mixed with HTML than curly braces. A separate templating language just wastes time.
    But if you're not careful then you could end up with template files like Mamboserver. Their the most horrible thing I've laid eyes on.

  22. #22
    SitePoint Wizard Hammer65's Avatar
    Join Date
    Nov 2004
    Location
    Lincoln Nebraska
    Posts
    1,161
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Dan Grossman View Post
    I also do as Mike B does in template files. The colon and endforeach/endif/etc syntax makes things clearer when mixed with HTML than curly braces. A separate templating language just wastes time.
    Sometimes the point of a template system isn't to save time. Rightly or wrongly, our designer is a little scared of PHP. She's a good designer, and that is what we pay her for after all. Using templates, lets her do what she does and lets me do what I do. For less complex projects we can use includes or code at the top or includes in various places in the HTML.

    I am all for doing MVC where it can be done, or at least TRYING to separate business logic from presentation. I am no different than anyone else here, I like to be able to quickly scan code, understand it, and modify it if necessary with a minimum of time. I don't however believe that applying principles of DESKTOP program design, always applies to the web. If for no other reason than that the presentation is not normally done programmatically, but done with a document format.

    A document format complex enough, that constructing it with an API is sometimes overkill and much too verbose. For small projects you need to be able to mix the document with the code in some ways sometimes.

    Then you have CMS systems that put together pages in blocks, for the sake of customization and ease of use for non-technical users.

    There is a misunderstanding about template systems such as Smarty. Though you can certainly set it up to do so, Smarty doesn't replace placeholder values and other tags in a tpl file with values you assign, every time you request a page. That may be the way some systems work, but Smarty compiles templates into the very kind off mixed PHP/HTML pages that everyone is discussing here.

    As far as being able to remember values that you set in logic code at the top of a page or in an include, when you get down into the HTML below. I may be getting old, and I don't know about anyone else here, but I don't have any problem with that. I don't know how you could expect to do a complex OOP project, or any other project if your memory about what you are doing in your code, wasn't any better than that.
    Last edited by Hammer65; Oct 21, 2007 at 10:43.

  23. #23
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by bokehman View Post
    The crap thing with having HTML sections in your code is that the HTML section is echoed automatically rather than returned.
    If that's not appropriate, then use output buffering to capture it. I'm sure that's what Symfony does before decorating the action template with the layout.

  24. #24
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    @hammer65: well said.

    It all comes down to the programmer(s). If you prefer to separate input, processing and output, do so.
    If you prefer to mix code/presentation, go ahead.

    There are times when separating code just makes life more compicated. For example vBulletin, the system they use just over-complicates everything.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  25. #25
    . shoooo... silver trophy logic_earth's Avatar
    Join Date
    Oct 2005
    Location
    CA
    Posts
    9,013
    Mentioned
    8 Post(s)
    Tagged
    0 Thread(s)
    Just remember what ever means you chose that you stay consistent though out the application, don't jump around different styles.

    *has a fit when code doesn't match my style, and goes on a rampage to reformat it -.-*
    Logic without the fatal effects.
    All code snippets are licensed under WTFPL.



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •