Jump to content

Horrible bad OOP - please help me make it perfect


zeezack

Recommended Posts

//Request Form Class - currently grabs departments and puts them into a select box

class request

{

 

// Define the function getList() - no parameters   

    function getList()

    {

include "includes/data1.php";

    $dep .='<select name="department">';    

$query_result = mysql_query ("SELECT * FROM `table` WHERE `condition` ='yes' ORDER BY 'apricot' DESC");

while ( $row = mysql_fetch_array($query_result) )

{

$orgcode = $row["code"];

$codelen = strlen($orgcode);

if($codelen==3)

{

$dep .='<option>'.stripslashes($row["name"]).'</option>';

}

}

$dep .='</select><br/>';

        return $dep;

        mysql_close($Link);

        include "includes/data2.php";

    }    

}

 

Link to comment
Share on other sites

"Turning something into OO" is kind of an abstract concept. I'm guessing you're asking how to incorporate OOP into your design.

There's many ways you can do it, and here are a few:

  • Use the mysqli extension so that you can access your MySQL databases using an OOP design.
  • Abstract your database access so you can plug in drivers for other engines (like PostgreSQL).
  • Use some sort of form-building library to make your combo box for you, possibly making an easy-to-establish 'connection' between your database driver and your combo boxes.

 

And to add the usual response:

You can get a lot if you look at a few of the frameworks and CMSes out there, not just concerning OOP but general application design. Some may fit your tastes, some may not. To name some of the popular ones: Drupal, Joomla, MediaWiki, CakePHP, CodeIgniter, TangoCMS. The list goes on. A design pattern that most of them seem to incorporate is MVC, something you may want to look into too.

Here goes the plug: I'm developing Thacmus, a small framework/CMS, aiming to keep it simple. I wouldn't say that it comes anywhere near the applications listed above, but it could also give you some insight (it might or might not be bad influence concerning my practices...).

To do what you had there, this is an attempt in Thacmus (didn't really test it...):

//Define database class
class Department extends DBI {
public $name, $code, $condition, $apricot;
static $table='table', $db_var=array('name','code','condition','apricot');
}
...
//Get and render the list
$list=array();
$temp=new Department(); //Use a 'template' class
$temp->condition='yes';
$temp->readAll($list,"where [=condition] and length(`code`)=3 order by `apricot` desc"); //Uses query formatting - also put length condition into query to simplify things
//Scan list
//Create comob
$combo=new FieldCombo('department',$list);
$input=//Whatever you may get from $_GET or $_POST
echo $combo->render($input);

Other people / frameworks / CMSes do it their own way. It's just an option.

Link to comment
Share on other sites

Well, not exactly. My design is a little different from most others, in that the actual connection information isn't stored in an object (something instantiated by new), but instead as statics in the database interface class.

[i probably should change this later on... The fact that I can't explain this well is kind of a bad sign :( ]

 

The classes from the Thacmus framework for this portion of code:

  • DBI [ /db/dbi.php ] - The static members / variables store the overall connection information. From there, each class that needs access to store information about itself in the database implements this class.
    As you can see, Department has to store information about itself, so it extends the DBI class (inheritance, polymorphism). The DBI class defines the base functionality for direct interaction between the database, i.e. querying the database and storing the information in the right variables / members, sending an insert / update query to save data, all the while escaping the data to prevent injection attacks. The readAll() method is an example, which specifies a condition to work off of, such as actual conditions ('[=condition]' which is expanded to "`condition`='yes'"), pagination (ex 'limit 0, 50'), sorting ('order by `column`'), and so on.
  • Field [ /lib/field/main.php ] - Specifies a general way to handle data through, well, fields - how to take input and give output, render the field with a certain value, etc. The heavy amount of abstraction in the Field allows it to easily interact with Form, handling the data for an object, which in effect makes it easier for Editor [ /lib/editor.php ] to handle database objects.
  • FieldCombo [ /lib/field/common.php ] - Extends FieldList (in same source file), which extends Field. These specify how to handle a list of data. The only real difference between FieldCombo and FieldList is that $size is 0, which makes the 'size' attribute of <select> 0, which turns it into that combo box.

Most of this can be found in the Tutorials section. I'm probably typing too much now.

 

In this case, the SQL query for the database instance isn't actually an object. It's just used in the database instance, which in this case is $temp, an instance of Department. The call to $temp->readAll() uses the information in the object itself, the $temp dummy, to determine what class it is and the table information. From there, it queries the table specified in the highest-level static of $table (which in this case will resolve to 'table') with the attached conditions, reads all of the result rows into new Department objects, which are pushed onto the array $list.

 

I apologize if the terminology is a little too heavy. If you need to know what something is, just ask.

 

Also need to make a correction in my previous post's code:

//For the combo box:
$data=array();
foreach ($list as $obj) $data[$obj->id]=$obj->name;
$combo=new FieldCombo('department',$data);

Before I had the combo's take in data from the objects themselves, which didn't make sense. Now this gives the combo a list that associates the object's id (corresponding to its row in the table) to its name. This, of course, assumes that the table structure has the autoincrement column `id` defined (according to the design for DBI).

Plus, since so little data is used in the query, it might be a little more efficient to specify which columns are needed ('select `id`,`name`').

 

Hmm, at the moment the servers are down at the moment. Should be up within a little while. To download the source code: http://sourceforge.net/projects/thacmus/

EDIT: It's up now.

Link to comment
Share on other sites

mmm

 

I am kind of new to the world of object orientated php. I was never taught web design, but I just picked up procedural methods. I did oo in JAVA.

Are there any good books that can help me build my own frameworks etc...never used Zend etc...

 

I would like to learn how to build

 

- database connections

- news blogs

- login and sessions

 

Finding this oo stuff really hard to work with in php, I've read the examples but in terms of making more sophisticated code, well never been given the opportunity. Any links or books that would help a lot?

Link to comment
Share on other sites

To verse yourself in the basics of OOP in PHP, the manual is an invaluable resource. For myself, I learn best primarily through example. The manual provides simple samples along with explanations of how they work. I never got a book myself, so I can't suggest one off the top of my head. In addition to the manual, of course, you can look at other open source projects and see how they might do things.

[OOP in PHP is somewhat similar to Java's as far as referencing goes (and maybe a few similar keywords), but after that they do a few things differently - the languages themselves are different]

 

In case you don't already have one, get a test server to mess around in. I'd suggest XAMPP to start off with - make sure that the server has PHP 5 (the PHP 4 end-of-life was a few months ago).

Make yourself a 'sandbox' directory, and just start coding. If you see an interesting example, copy and paste it, run it. Next, just mess around with it. Make something random, make something useful, it doesn't really matter since you're in the learning stage. In fact, it would probably be best just to try out the random stuff.

 

The more specific stuff can be found through googling for php tutorials.

Link to comment
Share on other sites

OK so if I give the example of making a simple news blog...

 

an admin logs in, then creates a new news article with pictures...what would be the best way to start and what coding technologies...

 

login check

picture check - upload

news

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.