OOP Best Practice? echo

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: OOP Best Practice? echo

Post by Christopher »

I think your Presentation code would be more like:

Code: Select all

<p>Please choose from the list below:</p>
<ul id="mylist">
<?php
$test= new NewClass();
$test->dbCheckList("membership","mem_id","mem_name");
 
foreach($test->row as $value){
    //check box code
     echo "<li>$value</li>\n";
};
?>
</ul>
That is essentially Model-Presentation. A further separation would be to create the class and fetch the data outside the template, and then somehow give $row to the template, such as:

Code: Select all

$test= new NewClass();
$row = $test->dbCheckList("membership","mem_id","mem_name");
inlcude 'mylist.php';
The the template file mylist.php would just be:

Code: Select all

<p>Please choose from the list below:</p>
<ul id="mylist">
<?php
foreach($row as $value){
    //check box code
     echo "<li>$value</li>\n";
};
?>
</ul>
This example is essentially MVC, where NewClass is the Model, the script that creates the object and does the include is the Controller, and the template is the View. You can see the progression in thought here. That's really all there is to MVC. ;)
(#10850)
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Re: OOP Best Practice? echo

Post by psurrena »

Everah wrote:It might not. Would all of the database interaction for a given controller be in the class you are using?
For generating form lists / check boxes, yes.
arborint wrote:This example is essentially MVC, where NewClass is the Model, the script that creates the object and does the include is the Controller, and the template is the View. You can see the progression in thought here. That's really all there is to MVC. ;)
So...is the class the model, the template the view and the controller is the file that brings them together?
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Re: OOP Best Practice? echo

Post by psurrena »

Also, why would you include a file instead of making a class for displaying? Isn't the class much more versatile?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: OOP Best Practice? echo

Post by RobertGonzalez »

Generally speaking your model handles the data interaction with the data stores (database, files, etc). The Controllers will go to the data stores through the Models based on the request of the user (usually, though sometimes the Controllers process data requests automatically - think fetching page data). The data is processed in some fashion then some data, whether it is the data fetched from the Model or something else, is handed off to the view for display.

I wrote a CLI application recently that followed a scheme similar to the attachment below. This is just one way to do it (the views were simple text outputs that were ultimately called into play by the bootstrap file, which could also be a front controller in some cases). I am sure there are other, better ways, but ultimately it is going to come down to how you plan your architecture overall.

I like to think in terms of flexibility and extensibility of the app later. Designs that are nimble make for faster development later on.
Attachments
UML diagram of a controller implementing an interface while composing a Model which composes a Db handler.
UML diagram of a controller implementing an interface while composing a Model which composes a Db handler.
Controller-Model-Interface-Scaled.png (41.02 KiB) Viewed 506 times
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: OOP Best Practice? echo

Post by Christopher »

psurrena wrote:So...is the class the model, the template the view and the controller is the file that brings them together?
Yes that is the essence of it. The dependencies are particularly important. An important point is that the Model is completely independent from the Controller or View. The Model is conceptually in the Domain layer below either the Controller or View which are in the Presentation layer. So you should feel freer in mixing View and Controller code if it makes sense. But if you mix in Model code then you are implementing the Transaction Script pattern and need to be aware of the consequences of that significant choice.
psurrena wrote:Also, why would you include a file instead of making a class for displaying? Isn't the class much more versatile?
You could, it really depends on the complexity of the problem. Simply including a PHP script as the View is what the Zend Framework does by default for example. As you rightly sense, it is not the cleanest, clearest way to implement it. MVC does not specify how the separations are created or enforced, only what the separations are. The fact that Front/Action Controller architectures nicely lend themselves to isolating the Controller code makes FC/AC the current best practice for MVC. But there is a some variation in opinion as to the exact implementation. However if you squint, all the major frameworks are essentially doing what I showed above -- just using the conventions and trade-offs they think are best.
(#10850)
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Re: OOP Best Practice? echo

Post by psurrena »

arborint wrote:So you should feel freer in mixing View and Controller code if it makes sense.
Which is:

Code: Select all

<?php   
$test= new NewClass();
$test->dbCheckList("membership","mem_id","mem_name");
 
foreach($test->row as $value){
    echo "<li>{$value}</li>";
};
?>
Right?

MVC is a new world for me, but is really interesting. Thanks for everyone's help.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: OOP Best Practice? echo

Post by superdezign »

That's definitely a step in the right direction. ^_^
dbemowsk
Forum Commoner
Posts: 82
Joined: Wed May 14, 2008 10:30 pm

Re: OOP Best Practice? echo

Post by dbemowsk »

Just to inject my two cents. I typically use a framework that I created where I set template tags to an array. Since the framework is modular, the last module that runs is the display module which takes all the generated tag data and runs it through a simple template parser class which will basically do a str_replace to a template and insert all the needed display data. I even use the template parser class to generate smaller parts of the whole page.

So, all your code should generate your output into a large array. There should be no echoing/printing of display output. The only thing I use that for is an occasional test of some code, but I then revert the code back to it's natural flow.

I like templating because it keeps a consistent look to all your pages and reduces redundancy. I have a short article on creating and using templates on my site.
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Re: OOP Best Practice? echo

Post by psurrena »

That sounds interesting, can you post a small example?
dbemowsk
Forum Commoner
Posts: 82
Joined: Wed May 14, 2008 10:30 pm

Re: OOP Best Practice? echo

Post by dbemowsk »

Well, a very basic example of a template would be like this.

Code: Select all

 
<html>
  <head>
    <title>{title}</title>
  </head>
  <body>
  <table>
    <tr>
      <td>{header}</td>
    </tr>
    <tr>
      <td>{body}</td>
    </tr>
    <tr>
      <td>{footer}</td>
    </tr>
  </table>
  </body>
</html>
 
This template has 4 tags. Title, header, body and footer. This template would be saved to a file like "mytemplate.tpl". Your template parser and display functions/classes would work like this:

Code: Select all

 
<?php
//do our needed includes
include 'templateparser.php';
include 'display.php';
 
//here we'll set our tags
$tags['title'] = "My Hello World Page";
$tags['header'] = "This is the header to my Hello World page.";
$tags['body'] = "Hello World";
$tags['footer'] = "This is the footer to my Hello World page.";
//we may have some other code in here
$output = templateparser::parse($tags, "mytemplate.tpl");
 
//now we'll call our display page
display($output);
?>
 
Basically all your template parser would do is take your $tags key names, add the "{...}" to create the tag, and then do a str_replace on the contents of the template file with the $tags values. It would then return the resulting HTML code. Your display function would then do any outputting to the browser.

Your tags can be in any format you like. I chose "{tag}", but you could choose anything. "&tag&", "%tag%", "%tag&" ...

Granted this is a very basic example, but it should give you an idea of how it works.

Now if you are looking for an example of a framework, these typically are not simple enough to post an example here. If you do a google search on "php simple framework" there are some good examples out there.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Re: OOP Best Practice? echo

Post by RobertGonzalez »

<rant>I can quickly see this becoming a debate over using a template engine and not using a template engine. Please try to keep this on topic with the original post.</rant>
Getting back to what was originally asked, I think the overwhelming consensus here is that functions should return stuff and the view layers should output it.
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Re: OOP Best Practice? echo

Post by psurrena »

dbemowsk, I like it, thanks for showing.

Everah, thanks for all your help.
dbemowsk
Forum Commoner
Posts: 82
Joined: Wed May 14, 2008 10:30 pm

Re: OOP Best Practice? echo

Post by dbemowsk »

Sorry everah, I had no intention of starting a heated debate.
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Re: OOP Best Practice? echo

Post by psurrena »

Not to add to the fire but, here's my current system...

index.php

Code: Select all

<?php
    require_once('library/config.php');
        $mode=$_GET['mode'];
    
        switch($mode){
            //work
            case("2"):
                $content="pages/work.php";
                break;
 
            //Contact   
            case("4"):
                $content="pages/contact.php";
                break;
                
            //Home
            default:
                $content="pages/default.php";
    }
    
    require_once('library/template.php');
?> 
for example, contact.php

Code: Select all

 <a href="index.php"><img src="images/contact.gif" width="200" height="30" alt="Contact Image"/></a>
<div id="leftCopy">
    <p>Please feel free to email me with any questions or comments.</p>
    <p><?php echo "<a href=\"mailto:{$email}\">{$email}</a>"; ?> 
and my template

Code: Select all

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>Title of Page</title>
</head>
<body>
    <div id="container">
        
        <?php require_once($content); ?>
            
    </div>
    <div id="footer">
        <p>footer stuff</p>
    </div>
</body>
</html> 
Just thought I'd share
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Re: OOP Best Practice? echo

Post by Mordred »

dbemowsk wrote:Sorry everah, I had no intention of starting a heated debate.
Hi, you're invited to join the moderately heated debate at viewtopic.php?f=19&t=83839, where we currently look for the hot water tap in template engines ;)
Post Reply