Jump to content

Some OO questions


ShaolinF

Recommended Posts

Hey Guys

 

I have two questions:

 

#1 When working in OOP how should I connect to the DB - Should I create a function in the class which connects to the DB or should I just create a php file and use the include method instead ?

 

#2 One thing that has been really bugging me is how do I extract/manipulate DB data when using classes. So for example:

 

public myClass {

private $id, $name, $address;

function __construct() {}

function getName() {}

}

 

With the example class above, how would I get the name from the DB using the "getName" method ?

Link to comment
Share on other sites

Hello! I'm not sure if this will help you understand more but hope it helps

 

Creating a MySQL(Or whatever database you are going to use) class would come in handy. You would have to just add the class and initialize it

 

This is just an example:

class MySQL_Class {

                var $links;

                var $queries;

               

function MySQL_Class($links (array)) {

 

mysql_connect($links['host'],$links['user'],$links['pass']);

 

mysql_db_select($links['dbname']);

 

}

 

function query($queryTo) {

 

mysql_query($queryTo);

 

}

 

function getName($table,$name) {

$r = mysql_query('SELECT $name FROM $table');

 

return mysql_fetch_array($r);

}

 

}

 

Do note, this is just a pretty beat up example, you could probably get creative like using arrays to update the rows and so on. Hope you got an idea on how it would look.

 

All you would have to do is $db = new MySQL_Class($links);

 

$db->query() etc etc

$db->getName('phpfreaks','allenskd');

 

Link to comment
Share on other sites

In his code, $links is an array of database connection information passed to the constructor (check the function declaration).

 

Okay, now.  A singleton database class follows the Singleton design pattern, as you probably could tell from the name.  It works by making one instance throughout the whole class.

 

class Database {

      protected $instance;

 

      public static function getInstance()

      {

            if (!$instance) {

              self::$instance = new Database();

            }

            return self::$instance;

      }

}

 

That's how the singleton pattern works. Obviously you'd need to connect to the DB somewhere in there though.

You'd also probable have some other things in there too though, for queries and such.  You'd get the instance like this:

 

$db = Database::getInstance();

Link to comment
Share on other sites

Well, the singleton pattern does just what it sounds like -- it creates only one instance of a particular class throughout the whole script.  For example:

 

$db1 = new Database();
$db2 = new Database();
if ($db1 == $db2) {
  echo "Same.";
}
else {
  echo "Different.";
}

 

That'll output "Different." because it's two different instances. On the other hand:

 

$db1 = Database::getInstance();
$db2 = Database::getInstance();
if ($db1 == $db2) {
   echo "Same.";
}
else {
  echo "Different.";
}

 

That will echo "Same."

Link to comment
Share on other sites

Ah, I see. Isnt the == operator comparing references ?

 

Would this cause problems if multiple requests were being made by different users ? Another question related to this issue, if I have a script which creates an instance of a class and two people access that script, will it create a problem if I want to run methods/functions since you have two instances with the same name?

Link to comment
Share on other sites

Don't think you need to worry about Singletons at this part in your OOP learning.

 

I also think the class mentioned above is particularly damaging. Why pass an array of input parameters when you can just as well specify it in the constructor? Because you want to cause yourself and anyone using your code a headache.

 

<?php

class SQLException extends Exception {
    public function __construct($msg) { parent::__construct($msg); }
}

class MySQL {
    private $connection = null;
    private $database_name = null;

    public function __construct($host, $username, $password, $database_name) {
        $this->connection = mysql_connect($host, $username, $password) or throw new SQLException("Could not connect to database");
        mysql_select_db($database_name, $this->connection);

        //set the 'name' of the database
        $this->database_name = $database_name;

    }

    public function getName() { return $this->database_name; }
}
?>

Link to comment
Share on other sites

Top stuff guys.

 

keeB - The getName() returns the DB name - what if I wanted to return a name of a customer on the DB?

 

So, I want to get started on my first OO project but I have come across a problem which I don't exactly know how to overcome. I have 3 php files, the first is the website header, the second is the content and the third is the footer. I have an index.php and I simply include these 3 pages into the index.php - Now, the header file has a line of code which outputs the user's name, and the footer has a signout link. Now, how will I link the two? It would have been simple if all the files was just one script, I could create an instance and do what I need, but in this case I am including all the different files... I hope this makes sense.  :-\

Link to comment
Share on other sites

define the header file as a function

 

header.php

 

<html>

<head>
<!-- some head information --!>
</head>

<?php
function header($userId) {
     echo $userId;  
}

<!-- the rest of the header in html --!>
?>

 

index.php

 

<?php

include ("header.php");
$userId = get_current_user_id(); //i dont know, i made this up.
header($userId);
?>

 

This is PHP Help related code though, so I won't delve any deeper.

Link to comment
Share on other sites

Well sorry 'bout that :(

 

To tell the truth i'm still on the php4 loop, been reading john klein's articles to get my act together. Well, you'll be seeing me around (or I'll be in despair) since I myself have questions regarding application design etc etc :)

 

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.