Jump to content

Archived

This topic is now archived and is closed to further replies.

wrave

[SOLVED] Coding Style and OOP

Recommended Posts

My PHP code looks like the spaghetti code that was always derided back when BASIC relied on GOTOs to get things done. I've got bits of HTML inside blocks of PHP and then I'll have a block of HTML code within a HERE document and find that I have to drop out of the HERE block to insert a line or two of PHP. This is almost impossible to read.

 

From the little reading I've done on OOP, I could use it to clean up my coding style quite a bit. Can anyone point me towards some information that might help me learn a better way to design my applications?

 

PHP amazes me. I've been able to write applications that I could never have done in any other language that I've used. I've got a lot to learn but I really have enjoyed working with PHP and MySQL. Now if I can just get a Linux box running Apache instead of this Win machine and PWS to do my development on, I think I'll have found the Holy Grail of application development.

 

Any pointers or suggestions would be appreciated.

Share this post


Link to post
Share on other sites

The best thing I've found to avoid spaghetti code is to use a MVC pattern and adhere to it.

 

GOTO 3

Share this post


Link to post
Share on other sites

1) Look into MVC + 1

2) Avoid heredoc syntax

3) Start using a template engine

 

It's one thing to mass applicaiton logic with business/domain/model logic but it's the WORST when people mingle HTML with PHP...that gets horribly messy super fast.

 

Change that pronto. :)

Share this post


Link to post
Share on other sites

Thanks for the suggestions koen and Hockey.  :)

 

I'm not sure what "MVC pattern" is? I'll look for that.

 

I once had a site template engine installed but abandoned it because of the learning curve. I've been writing HTML by hand for years and am more comfortable coding pages this way. But if I could get a template engine to do what I want, I would probably use it. Do you have any suggestions?

 

Damn! There go my heredocs!

 

Thanks again.

 

Frank

 

Share this post


Link to post
Share on other sites

Template engines are'nt usually required, especially when your using an mvc implimentation. An example of a view in html/php compared to some template engine...

 

<html>
  <head>
    <title><?php echo $title; ?></title>
  </head>
  <body>
    <?php foreach ($articles as $article): ?>
    <h1><?php echo $article['title']; ?></h1>
    <p><?php echo $article['body']; ?></p>
    <?php endforeach; ?>
  </body>
</html>

 

<html>
  <head>
    <title>{title}</title>
  </head>
  <body>
    {loop='article'}
    <h1>{title}</h1>
    <p>{body}</p>
    {loop end}
  </body>
</html>

 

Even though I used some pseudo coded template engine in my example, I really don't see that the php version is that much harder to impliment / has a greater learning curve for designers. And I guarantee the php version will be faster.

Share this post


Link to post
Share on other sites

Template engines are the devil's spawn. It only adds an extra syntax for you to learn, which is pointless.

Share this post


Link to post
Share on other sites

The argument goes both ways, but I also fall into the 'avoid the template engines' crowd.  PHP is meant to intermingle dynamic data with static data, so why invent another tool to do what the language does natively.

 

When I first learned PHP, the book I was reading suggested creating template files:

<i>greeting.html</i>

<p>
  Welcome, {USER_NAME}!
</p>
<p>
  Your last login was {LAST_LOGIN}.
</p>
<p>
  Lorem ipsum ...
</p>

To display the page:

<i>some_file.php</i>

<?php
  $greeting = file_get_contents('greeting.html');
  $greeting = str_replace('{USER_NAME}', $username, $greeting);
  $greeting = str_replace('{LAST_LOGIN}', $last_login, $greeting);
  echo $greeting;
?>

It worked fine, but it becomes messy in larger sites.  Also, if there are a lot of {VARIABLES} to replace in the template, that will be a lot of calls to str_replace which will just keep processing the same text over and over and over; it's horribly inefficient.  Another drawback, and I don't know why I didn't organize it better, was I stuck all the template.html files in a single directory; it became impossible to manage.

 

For several months that's how I did it on my own personal site.  Then I got the job where I work now and inherited my current project that I still maintain.  At the time I inherited it, there were many, many very large files that had PHP and HTML intermingled like you probably have in your own site now.  To make it worse, some of them had Javascript and CSS embedded as well.  Try sorting through a file one thousand lines long with four different languages in it and on average a <?php or ?> on every other line.  IMPOSSIBLE!  Because of the horrible entanglement of jumping between PHP and other languages in these files, I was instantly turned off by any method that jumped in and out of PHP-mode frequently.

 

After a while it hit me that the str_replace() method sucked and needed to go.  I had heard of template engines and knew the basic idea, but I didn't want to go that route; I see them as only making one pain in the ass a bigger pain in the ass.  Then it hit me (and I already said it once in this thread):

PHP is meant to intermingle dynamic data with static data.

 

Now as I semi-mentioned before, other programmers' code that I'd seen that constantly jumped in and out of PHP were difficult to read.  I finally came to the conclusion the ability jump in and out of PHP was a good approach and people were right to use it, but also that many were misusing it and creating difficult to maintain code.

 

I finally decided I would start programming this way as well, but with one major rule:  As little logic as possible should go into these files; if any logic does need to be in the file, then it should be at the beginning.  Basically, there should be as little intermingling of PHP with other languages as possible.  I called these files components as they were mainly meant for displaying visual pieces of a web site; now that I've looked into cakePHP and MVC a little, I see that they're more commonly called views, but the concept is the same.

 

Here is sample home page for a cakePHP site that displays the recent news and recent comments, as well as prompting the user to login if they haven't done so already.  $recentNews and $recentComments are incoming arrays that will be populated with the entries to display.  Since there is a bit of looping and other stuff to be done before the news and comments can be displayed, it would be messy if placed within the HTML.  Therefore, to help readability, I place it at the head of the script and store the output in variables.  Then in the HTML I use a <?=$var_name?> to print the items.  I find that it makes reading the markup much easier.

<?php
  // RECENT NEWS
  $News = '<p>Nobody has reported any news yet!</p>';
  if(!empty($recentNews)){
    $News = Array();
    foreach($recentNews as $news){
      $News[] = $this->renderElement('news/recent', $news);
    }
    $News = implode('', $News);
  }
  
  // RECENT COMMENTS
  $Comments = '<p>Nobody has commented on anything!</p>';
  if(!empty($recentComments)){
    $Comments = Array();
    foreach($recentComments as $comment){
      $Comments[] = $this->renderElement('comments/recent', $comment);
    }
    $Comments = implode('', $Comments);
  }
  
?>

<p>
  Welcome to the Test Site!
</p>
<?php if(!$session->check('User')){ ?>
  <p>
    Please <a href="/users/login">login</a>.
  </p>
<?php } ?>

<!-- RECENT NEWS -->
<div>
  <h1>Recent News</h1>
  <?=$News?>
</div>

<!-- RECENT COMMENTS -->
<div>
  <h1>Recent Comments</h1>
  <?=$Comments?>
</div>

Share this post


Link to post
Share on other sites
Basically, there should be as little intermingling of PHP with other languages as possible.  I called these files components as they were mainly meant for displaying visual pieces of a web site; now that I've looked into cakePHP and MVC a little, I see that they're more commonly called views, but the concept is the same.

 

I would think (using MVC) that most of that logic in the top of your view should actually be in the page controller, maybe even as far back as the model.

Share this post


Link to post
Share on other sites

Basically, there should be as little intermingling of PHP with other languages as possible.  I called these files components as they were mainly meant for displaying visual pieces of a web site; now that I've looked into cakePHP and MVC a little, I see that they're more commonly called views, but the concept is the same.

 

I would think (using MVC) that most of that logic in the top of your view should actually be in the page controller, maybe even as far back as the model.

For the majority of logic to be performed, I agree.  But what about my example above of the recent news and comments.  You surely wouldn't put the code to display recent news in the model as it's not DB related.  Moving it into the controller is just about the same as keeping it where it is.  Placing those loops into the controller and then just passing the resultant markup into the view just moves the code from one location to another.  The code is for display purposes, not business logic, so who is to say it belongs more in the controller than it does in the view?

 

That view is tied to the PagesController, which is the "default" controller in cakePHP.  Ideally, I suppose the News and Comments controllers would have methods for retrieving the "recent items" snippets so that they could be called from other controllers, something like:

$NewsController->get_recent_news_snippet();

However, that function would merely be opening another view that performs the same formatting.  So again, the same code is moved into the same logical place.  (Although it does make more sense since it is now the news controller creating the view rather than the pages controller).

Share this post


Link to post
Share on other sites

roopurt18 and thorpe,

 

Thanks so much for the enlightenment. I think I am beginning to understand what you are explaining. I do have to admit that I am unfamiliar with some of your terms and am wondering if either of you could point me toward a reference that might help me grasp the "model/controller" constructs you are talking about. Is there a book or some on-line documentation either of you might recommend?

 

In general, I like to figure things out and don't like to bother anyone when I can avoid it. I know how busy you must be. But this is all pretty new to me. I have some education but (now I am giving away my age :o) most of these technologies came along after I was out of school. I'd love to find a job like roopurt18's where I might have access to some code written by someone experienced with this stuff. That'd be a great way to learn.

 

So far my projects are not very complex and I know as I go along I will see where I should have approached them from a different angle and ultimately, I'll probably find I have to go back and redesign everything from the ground up. (Ugh :-[) For example, I worked a few years with a very different DBMS from MySQL (MUMPS and Fileman) and as yet I have not used any OOP code in my projects although I have built some PHP functions to fetch data from the DB. I try to write generic functions but many of them turn out to be fairly project specific. Anyway...

 

I have the 2nd edition of the Ullman book "PHP and MySQL..." and have been using it as my text but I am also reading it pretty piece-meal. (That's a problem when you already know some of what you are reading...it get's boring.) This seems to be a very good book for an overall view of the project construction process. Are there others you might recommend?

(Maybe I should just read what I have, front to back, like it was intended.)

 

Anything that you might find the time to share will be helpful I am sure. And thanks so much for taking the time that you have already spent to get me on the right track. I am very appreciative.

 

Share this post


Link to post
Share on other sites

Whoa! I just went to the Wikipedia and now see what BIG questions some of mine are. Thanks again to any and all that find the time to reply. Ah yes, and I've finally learned what MVC (model, View, Controller) stands for!!! ;D

Share this post


Link to post
Share on other sites
That's a problem when you already know some of what you are reading...it get's boring.

 

Be careful when doing that.  Sometimes an author will take the time to point out a very particular nuance of a language in a section you think you already know and thus skip over.

 

The best way to get a leg-up on the MVC approach is to download an existing PHP framework and see how they do things.  I myself have been fiddling with cakePHP and so far the experience has been enjoyable.

Share this post


Link to post
Share on other sites

CakePHP isn't strictly MVC. There are many "shortcuts" taken that prevent it being so. Hard coupling for one.

 

The nuances I have with MVC include:

 

1) It's a buzzword, and thrown about like one.. CV/Resume.. marketing (See CakePHP and other frameworks) .. etc.

2) It is vastly over complicated. If your Applications Model, View and Controller are all separate from one another, you have achieved MVC. Separation does not require separate objects, it does not even require separate files. If you have you controller at the "top" of the page, the model in the "middle" of the page, and the View at the "bottom" you have achieved MVC.

Share this post


Link to post
Share on other sites
CakePHP isn't strictly MVC. There are many "shortcuts" taken that prevent it being so. Hard coupling for one.

Would you be willing to provide an example?  I've barely scratched the surface of MVC myself and I think it's pretty clear you have extensive experience in this area.

Share this post


Link to post
Share on other sites

http://api.cakephp.org/controller_8php-source.html

 

You can see some hard coupling in that source. Hard coupling prevents objects from being truly separate, thus you cannot achieve true MVC if you can't separate.

 

CakePHP also has a few singletons, which I frown upon, but that is not relevant to this discussion. :)

Share this post


Link to post
Share on other sites

Way too tied into the model.. Some of these methods operate on the guts of the model. The Controller should just use a thin interface to message the model, not actually operate on it.

Share this post


Link to post
Share on other sites

I grabbed a copy of cake and have installed it but am having problems with setup and configuration. I can currently read the initial page and will go ahead from there.

 

In my research I discovered BareBones and it seems to me that it would be a pretty good place to begin trying to understand all that MVC is, except I haven't found much in the way of documentation.

Share this post


Link to post
Share on other sites

2) It is vastly over complicated. If your Applications Model, View and Controller are all separate from one another, you have achieved MVC. Separation does not require separate objects, it does not even require separate files. If you have you controller at the "top" of the page, the model in the "middle" of the page, and the View at the "bottom" you have achieved MVC.

 

Kinda.  I would agree you do have the MVC parts all in one file but what if you want to display a different set of data or display if differently and then when you start getting more data and large files it becomes more complicated to manage in one files.  I mean I am build a framework with that allows for MVC which after using it I really like it.  I mean typing this:

 

site.com/site/index

or

site.com?c=site&f=index

 

which will call in the code:

$site->index();

 

and then with that function I collect and form the data and the just do

 

$this->load_page($views);

 

with an array of view with there data and is just a lot easier to manage the php real code and the php view code.

Share this post


Link to post
Share on other sites

I've been programming for several years, both formally and informally. I feel like I've got a pretty good grasp on what's a good design... how to attack various problems. I've done OO programming for a good 5 years or so now. I've never heard so much about MVC as I have on this forum. So after a little reading and following of these threads I've come to the following conclusion:

 

MVC really isn't anything official. It's not a formal methodology so much as a concept. Basically what MVC suggests is that you separate your Data layer (model) from programming/business logic (controller) from the presentation (view). There's really not a single implementation or way of doing it.... if you separate the various components in the way mentioned above... you technically have an MVC architecture.

 

Again, I'm no expert on this matter but that's basically where I've landed. Can you guys please confirm or correct me?

Share this post


Link to post
Share on other sites

I would agree that their is no one set way of implementing this.  MVC is more of a concept of, like you said, separating data, logic, and presentation.

Share this post


Link to post
Share on other sites

You've over complicated it again :)

 

MVC is a Design Pattern, "Concept" over glorifies it. It literally is Model, View and Controller separate from each other - that is it. The one file separation still satisfies MVC. The moment you start thinking about anything else other than this separation, you have overcomplicated it, and are in actual fact thinking of generic application design, or everyday OO practices, or whatever.

Share this post


Link to post
Share on other sites

This reminds me of when people say they know Ajax... there's really not anything to know. If you can program javascript (httprequest) program in a server side language (php) and then process the data you get back... You know Ajax. It's just a fancy word.

Share this post


Link to post
Share on other sites

OK, here's where my travels have brought me this day.

 

I'm not sure I need MVC the way it is being discussed so far in these pages. By that I mean MVC may be what I need to clean up my code, but I'm just not sure...here, I'm going to expose myself!  :o

 

<?php

$db = 'test';

$tbl = 'schedule';

$start_date = date("Y-m-d");

//Set $venue = location table 'id' value
if (isset($_POST['loc'])) {
  $venue_id = $loc = $_POST['loc'];
  //echo "It's Here!!!\n";
} 

echo <<<HTML_HEADER
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 

<html>

<head>
<LINK REL="stylesheet" TYPE="text/css" HREF="fathr.css" TITLE="Default">
<title>Freddy and the Hot Rods - Schedule Display</title>
</head>

<body>

<div ID="topBar">
<center>      
<P STYLE="color: 3366ff; padding: 5,5,5,5; font-family: Arial;
font-size: 14pt;"><H2>Freddy and the Hot Rods - Schedule Display</H2> 
</center>

<p>
<br>
<center>
<table bgcolor="#eeffee" border=0 cellspacing=0 cellpadding=0>
<tr>
<td>
<a href="http://localhost/php_db_tools/fathr_db_manager.php"> DB Mgr. Home </a> 
</td>
<td>  | <a href="http://localhost/php_db_tools/fathr_new_entry.php">New Venue Entry </a> |
</td>
<td><a href="http://localhost/php_db_tools/fathr_add_gig.php"> Add a Gig Date </a> | 
</td>
<td><a href="http://localhost/php_db/fathr_edt_menu.php"> Edit Contacts/Schedule </a>
</td>
</tr>
</table>
</center>

</div>



<div id="contentArea">
<h3>Freddy and the Hot Rods - Schedule Display</h3>
HTML_HEADER;

require_once("gen_db_func.php");

$row_color = array ('#ffffee','#ddeeff');
$row_color_idx = 0;

/****************************************************
* DISPLAY A LIMITED SET OF SCHEDULE DATA           *
***************************************************/

echo "<center><br />\n";
echo "<table border=0><br />\n";
echo "<tr bgcolor=\"#aaeecc\">";
echo "<th>Gig Date</th>";
echo "<th>  </th>";
echo "<th>Location</th>";
echo "<th>  </th>";
echo "<th>Start Time</th>";
echo "<th>  </th>";
echo "<th>End Time</th>";
echo "</tr>";

$conn = mysql_connect('localhost','user','password');
$query = "USE $db";
$result = mysql_query($query);
if (!$result) {
  die('<p>Invalid DB query: ' . mysql_error()>"</p>");
}

$query = "SELECT schedule.id, schedule.gig_date, schedule.start_time, schedule.end_time, location.name FROM schedule, location WHERE schedule.gig_date >= CURRENT_TIMESTAMP AND schedule.p_location = location.id ORDER BY schedule.gig_date";
//$query = "SELECT schedule.id, schedule.gig_date, schedule.start_time, schedule.end_time, location.name FROM schedule, location WHERE to_days(schedule.gig_date) >= to_days(now()) AND schedule.p_location = location.id ORDER BY schedule.gig_date";

$result = mysql_query($query);

while ($row = mysql_fetch_array($result,MYSQL_NUM)) {
  if ($row[1]>=$start_date) {
   echo "<tr bgcolor=\"$row_color[$row_color_idx]\">
         <td>$row[1]</td>
         <td>  </td>
         <td>$row[4]</td>
         <td>  </td>
         <td>$row[2]</td>
         <td>  </td>
         <td>$row[3]</td></tr>\n";
$row_color_idx = 1 - $row_color_idx;
  }
}

?>

This is the kind of code I've been writing. To keep with the intent of this forum, I am not asking for coding help. This code works just fine (I am hoping the "pre" tags will present this so you can read it.) and this is one of the better looking (i.e. most readable) files I have created in this application.

 

The intent is to build a schedule management system for my band. I can write this kind of code all day long and don't feel I need "cake" or anything else. What I am really looking for is a way to style my code so it is as readable as possible for maintenance and reuse.

 

Maybe I've missed the whole point of cake but it doesn't seem to me to be either any easier or make the code any more portable. With cake requiring elements of the code to be scattered in all those different directories, how does that make the system any more easy to understand?

 

From what I've read today, and I sincerely thank everyone that has contributed to this discussion, I'm probably going to continue doing what I've been doing. Still, I suspect there may be a way to build the code here so it IS MORE READABLE and that will make it more MAINTAINABLE as well as making it easier to adapt to similar applications.

 

Am I wrong or simply missing the whole point?

 

Please remember I am a newbie!  ::) (And maybe one that's not all that smart.)

Share this post


Link to post
Share on other sites

From your example file.

$query = "SELECT schedule.id, schedule.gig_date, schedule.start_time, schedule.end_time, location.name FROM schedule, location WHERE schedule.gig_date >= CURRENT_TIMESTAMP AND schedule.p_location = location.id ORDER BY schedule.gig_date";

 

Today that is the only file that uses that query.  What if tomorrow you need to pull that same information on another page.  No problem, you copy and paste the query, right?  The day after that, you change the table structure, so now you have to change the queries.  It's only two files and two queries, so it's not a huge deal, right?

 

Now pretend your project is massively complex and encompasses several thousand (or several hundred thousand) lines of code.  Those types of changes are not easily accomplished.

 

What it boils down to is application design is about duplicating as little code as possible.  If you have 10 files that all run the same query and there's a problem with the query, you have to fix 10 separate files.  If instead you have 100 files that all call the same function in another file, and you find a bug in that function, you fix it in one place and you've fixed it in all of them.

Share this post


Link to post
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.