TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 10-10-2007, 01:45 PM   #1 (permalink)
The Acquainted
 
Join Date: Oct 2007
Posts: 170
Thanks: 18
maZtah is an unknown quantity at this point
Default [Help needed] How to start building an OOP script?

Hi folks,

As you can read in my introduction-post I'm willing to master the OOP-skills.
I want to start my own OOP-project and will see where it ends.

For example, I want to start with a membersystem en newssystem, since those functions are needed in almost every CMS.

Now, what should I do to get off writing this piece of code?
Like what functions should I write in which order, etc?

Can anybody help me getting started?

Thanks in advance!

P.S. I'm not asking for any scripts, although everything is welcome. I just don't know where and how to start.
maZtah is offline  
Reply With Quote
Old 10-10-2007, 02:27 PM   #2 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

The first step is to step away from the computer and start planning things on paper. If you just go diving into coding your objects straight away, it will most likely end up as a huge mess!

Personally, I like to brainstorm the idea as the very first step. Start with whatever it is you're aiming to achieve ("Build a CMS") and branch out from there. Only when you know what exactly it is that you want to build, can you start building it.

Take your time and try to think more widely than just creating a list of 'systems' that you'll need.
Salathe is offline  
Reply With Quote
Old 10-10-2007, 02:48 PM   #3 (permalink)
The Reckoner
Advanced Programmer Top Contributor 
 
Karl's Avatar
 
Join Date: Sep 2007
Posts: 437
Thanks: 22
Karl is on a distinguished road
Default

Well the first thing before starting any project is to build a basic design, take a look at your system as a whole and decide what objects make up your system.

One class you will probably want to start with is a Database class. This class would provide methods that allow you to encapsulate and simplify the various database tasks that you need to perform. For example, I use something similar to:

PHP Code:
class Database
{
  private 
$m_pConn;
  ...

  public 
funciton __construct() { ... }
  public 
funciton connect() { ... }
  public 
funciton query() { ... }
  public 
funciton queryColumn() { ... }
  public 
funciton queryRow() { ... }
  ...

Inside the __constructor you would create a new database connection by calling the connect() function.

The connect function would create you a new database connection and store it in $m_pConn.

The query, queryRow and queryColumn methods provide simpler interfaces for performing common "SELECT" operations, for example, we could fetch a single member from the database using the queryRow method:

PHP Code:
$pDatabase = new Database();
$aMember $pDatabase->queryRow('SELECT username, email FROM members WHERE id = 4'); 
Don't get me wrong, this isn't going to be something you achieve in a night. It takes time to build efficient, reusable objects, but when you build them right, you can pop them into projects and reuse your code time after time.
Karl is offline  
Reply With Quote
Old 10-10-2007, 04:43 PM   #4 (permalink)
The Wanderer
 
cherries's Avatar
 
Join Date: Oct 2007
Posts: 20
Thanks: 0
cherries is an unknown quantity at this point
Default

a class declaration would be a good start(as Karl said):
PHP Code:
<?php
    
class myClass
    
{
        private 
$db;
        
        public function 
__construct ( )
        {
            
$this->db = new mysqli('localhost''x''y''z'); //Using mysqli is also a good idea.
        
}
    }
?>
cherries is offline  
Reply With Quote
Old 10-11-2007, 06:39 AM   #5 (permalink)
The Acquainted
 
Join Date: Oct 2007
Posts: 170
Thanks: 18
maZtah is an unknown quantity at this point
Default

Thanks for your replies. I don't get you very much, cherries.
Can you explain your post further?

Anyway, I've written some things down on paper, and started - how surprisingly - with a Database class.

So, thanks again for your kind replies.
maZtah is offline  
Reply With Quote
Old 10-11-2007, 11:43 AM   #6 (permalink)
The Acquainted
 
Join Date: Oct 2007
Posts: 170
Thanks: 18
maZtah is an unknown quantity at this point
Default

I've now written 2 classes, a Database and a Member class. I'm able to execute a query with the Database class, and find a member-name with the Member class by giving an member-id.

Am I heading into the right way? (PS. Don't mind security holes, yet)

PHP Code:
class Database {
    public function 
__construct() {
        
$this->connect();
    }
    
    public function 
connect() {
        @
mysql_connect('localhost''root''') or die('Could not connect to the database!');
        @
mysql_select_db("debron") or die(mysql_error());
    }
    
    public function 
query($string) {
        
$result mysql_query($this->secureQuery($string));
        return 
$result;
    }
    
    public function 
fetch($string) {
        
$result mysql_fetch_array($string);
        return 
$result;
    }
    
    public function 
secureQuery($string) {
        
$result mysql_real_escape_string($string);
        return 
$result;
    }
    
    public function 
disconnect() {
        
mysql_close();
    }
}

class 
Member {
    public function 
__construct() {
        
$this->db = new Database();
    }
    
    public function 
findById($int) {
        
$sql $this->db->query('SELECT Name FROM Members WHERE Id='.$int);
        
$result $this->db->fetch($sql);
        echo 
'<br /> <strong>Member with id '.$int.':</strong> '.$result[0];
    }
}

$db = new Database();
$blaat $db->query('SELECT Id, Name FROM Members');
echo 
'<strong>Names:</strong><br />';
while(
$row $db->fetch($blaat)) {
    echo 
$row['Name'].'<br />';
}

$test = new Member();
$test->findById(1);

$db->disconnect(); 
maZtah is offline  
Reply With Quote
Old 10-11-2007, 12:11 PM   #7 (permalink)
daz
The Contributor
Upcoming Programmer 
 
Join Date: Sep 2007
Posts: 31
Thanks: 0
daz is on a distinguished road
Default

Looks good. This is a MySQL database connection I wrote.
PHP Code:
define("DB_HOST""localhost");
define("DB_USER""root");
define("DB_PASS""");

interface 
Database {
    public function 
connect();
    public function 
selectDB($database);
    public function 
query($szQuery);
    public function 
queryRow($szQuery);
}
class 
MySQL implements Database  {
    public 
$result "";    
    private 
$szQuery "";
    private 
$connect;
    
    public function 
__construct() {
        
$this->connect();
    }
    public function 
__destruct() {
        
mysql_close($this->connect);
    }
    public function 
connect() {
        
$this->connect = @mysql_connect(DB_HOSTDB_USERDB_PASS
        or die (
"MySQL: Cannot connect to server!");
    }
    public function 
selectDB($database) {
        
mysql_select_db($database) or die ("MySQL: Cannot select database!");
    }
    public function 
query($szQuery) {
        
$this->result mysql_query($szQuery) or die("MySQL: Cannot perform query!");    
            if (
$this->result) {
                return 
true;
            }
        return 
false;
    }
    public function 
queryRow($szQuery) {          
        
$this->result mysql_query($szQuery) or die("MySQL: Cannot perform query!");    
            if (
mysql_num_rows($this->result) >= 1) {
                return 
true;
            }
        return 
false;    
        
mysql_free_result($this->result);

    }    

daz is offline  
Reply With Quote
Old 10-11-2007, 12:11 PM   #8 (permalink)
The Reckoner
Advanced Programmer Top Contributor 
 
Karl's Avatar
 
Join Date: Sep 2007
Posts: 437
Thanks: 22
Karl is on a distinguished road
Default

Nice start. Here are a few poiners.

1) Change the connect() method to accept arguments for setting up the database connection. THe connection details seem to be hard coded currently. Chanign this will allow you to easily reuse this object in future projects.

2) If you add some "wrapper" methods to your Database class for retrieving things such as a row, column or array of results (as I mentioned in my orignal post) then you could make your Member class much more flexibile and reduce the amount of repeated code.

Lets say you do add the wrapper functions (something like this):

PHP Code:
public function query($szSql)
{
    
$pResult mysql_query($szSql);

    ... 
convert result to array ...

    return 
$aResult;
}

public function 
queryRow($szSql
{
    
$aResult $this->query($szSql);
    return 
$aResult[0];
}

public function 
queryColumn($szSql)
{
    
$aRow $this->queryRow($szSql);
    return 
$aRow[0];

You can then perform the same query as before using:

PHP Code:
$pDatabase->queryRow('SELECT id FROM members WHERE id = 1'); 
You could wrap that in another "wrapper" function to give it a more user friendly interface, such as:

PHP Code:
function getById($iId)
{
    
$iId = (int) $iId;
    return 
$this->pDatabase->queryRow("SELECT id FROM members WHERE id = $iId");

Then to achieve the same thing, we simply use

PHP Code:
$aMember $pMember->findById(1); 
You could actually create another class for handling these database "interfaces". This other class would be similar to that of a Model from the MVC pattern, including helper functions for achieving things such as:

PHP Code:
// Fetch the Id from the member table with Id 1
$pMembers->setId(1);
$aMember $pMembers->fetch('id'); 
and

PHP Code:
// Fetch all members from the members table
$aMembers $pMembers->fetchAll(); 
I better stop there before I completely overwhelm you. Lemmie know if any of that makes any sense :)
Karl is offline  
Reply With Quote
Old 10-12-2007, 12:10 PM   #9 (permalink)
The Acquainted
 
Join Date: Oct 2007
Posts: 170
Thanks: 18
maZtah is an unknown quantity at this point
Default

Thanks for the good advice again.

Karl, may I ask where the 'p' stands for in $pDatabase and $pResult etc?

Cheers!
maZtah is offline  
Reply With Quote
Old 10-12-2007, 12:20 PM   #10 (permalink)
The Reckoner
Advanced Programmer Top Contributor 
 
Karl's Avatar
 
Join Date: Sep 2007
Posts: 437
Thanks: 22
Karl is on a distinguished road
Default

The p stands for an object pointer. See this article for more information on these conventions.
__________________
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
Karl is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 03:34 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design