TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Advanced PHP Programming (http://www.talkphp.com/advanced-php-programming/)
-   -   Tying classes together (http://www.talkphp.com/advanced-php-programming/3447-tying-classes-together.html)

Andrew 10-05-2008 08:00 PM

Tying classes together
 
Well, I'm reading my OOP book right now, but it doesn't seem to help me TOO much when it comes to tying classes together.

Basically, say I have a user class, which requires access to a database. What would be the best method to access the DB class within the user class? I would guess to have the user class extend the database class, but it doesn't make perfect sense, and also what if I needed another class within it, such as a Validation class?

Is it really good practice to include other class files into one class, and then create an instance within the class itself? Wouldn't that fall victim to including files which in turn also include files, which I'm assuming isn't good practice?

Any insight would be great. This is really driving me nuts, as it's the only thing that's keeping me from starting my project (I don't want to start coding it, and then realize the entire structure is 'wrong').

Enfernikus 10-05-2008 08:05 PM

Let's say the name of your DB class is MySQLAccess

PHP Code:


<?php

class user
{
    private 
$db;
        
        public function 
__construct(MySQLAccess $db)
        {
            
$this->db $db;
        }
}

$db = new MySQLAccess($dbInfo);
$user = new user($db);

?>

This way the user class will NEED the object MySQLAccess to start up or it'll give off a fatal error.

xenon 10-06-2008 06:59 AM

You can do that by using the composite design pattern, as Enfernikus showed you above, or you can choose the registry design pattern.

kjarli 10-31-2008 03:16 PM

Usually it's the first. You store the database object within your user object.

$user->setDatabaseAdapter(new My_Db_Adapter());


All times are GMT. The time now is 11:13 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0