...

View Full Version : Defining a class in a settings file



Cacus
11-09-2011, 08:14 AM
Hi all

Wonder if you can help. I have some classes for a database controller. The class lets you access the database through the same method names. eg

class mysqldb {
public function insertData()
}

class postgredb {
public function insertData()
}

So in your main scripts you only need to change the call new to use a different database. eg

$db = new mysqldb();
or
$db = new postgredb();

While this makes writing your code for a different db much easier is there a way to so something like this :

// In a settings file:
$dbaseType = mysqldb();

// In all other files you call the object with:
$db = new $dbaseType;

I know the above does not work but I think it highlights what I'm after.
I only define the class I want to use for a database controller once in a config file and all the calls are updated from this.

Cheers
Steve

Dormilich
11-10-2011, 10:46 AM
While this makes writing your code for a different db much easier is there a way to so something like this :

// In a settings file:
$dbaseType = mysqldb();

// In all other files you call the object with:
$db = new $dbaseType;

I know the above does not work but I think it highlights what I'm after.
I only define the class I want to use for a database controller once in a config file and all the calls are updated from this.

maybe you mean something like a Factory class?

class DBFactory
{
public static function create($type = "mysql")
{
// do some checks to verify the type
// e.g. a switch() statement

// instantiate class
$classname = $type . "db";
return new $classname();
}
}

$db = DBFactory::create("mysql");

be sure to protect/cover your API by Interfaces.

other than that you can save your once instantiated DB class in a Registry or Service Provider at initialisation time to get it once you need it (similar to the Factory, only that you save the type anywhere inside)

// not sure if this is 100% correct
class DBService
{
private static $type = NULL;

public function __construct($type = "mysql")
{
if (NULL !== self::$type)
{
throw new UnexpectedValueException("DB type is already set to " . self::$type);
}
// do checks …

self::$type = $type;
}

public static function getDB()
{
// prevent accessing unset $type …

$classname = $self::$type . "db";
return new $classname();
}
}

Cacus
11-10-2011, 06:55 PM
Hi

Thanks for the reply the factory class is just the ticket.

Steve

Fou-Lu
11-10-2011, 11:23 PM
I'd suggest that you interface these classes as well. A good part of the power when it comes to using OO is the ability to tightly control the objects in use. Using a common interface will allow PHP to typehint them when you need to pass them around different methods and functions. The interface is quite typically the bases used when creating factory patterns.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum