Reputation: 470
I need some guidance about an php object inheritage situation. I have: a configuration object like:
configuration{
var driver = 'mysql'; // or 'mssql';
var host = 'database_host';
var user = 'database_user';
var password = 'database_password';
var name = 'database_name';
}
two database handler classes:
class mysql{
public mysql(){} // connect
public query(){} // set a query
public result(){} // load result
}
class mssql{
public mysql(){} // connect
public query(){} // set a query
public result(){} // load result
}
and some kind of class controller:
class database{
public function __construct(){
$configuration = new configuration;
/*
* now, depending on the value of the $configuration->driver
* my database class must inherit methods from mysql or mssql class
*/
switch( $configuration->driver ){
case 'mysql':
// database inherit mysql methods
break;
case 'mssql':
// database inherit mssql methods
break;
}
}
}
usage like:
$database = new database;
$database->query( 'select * from some_table' );
$result = $database->result();
so, when I use my database class methods, depending on configuration object, I actually use mysql or mssql methods. the way i see it is not passible because I want my database class to inherit another class in the class constructor.
I was hoping that someone could give me an advice about how can I do this.. let's say.. the right way.
Thanks.
Upvotes: 0
Views: 154
Reputation: 470
If someone, as confusend as me, reads this post, this is the solution I found (after weeks of research - yes, after weeks):
using singleton pattern, create a parent class called database:
class database{
protected static $instances = array();
// method to create a new instance of this object
public function getInstance( $driver ){
$instanceid = md5( $driver );
if( self::$instances[ $instanceid ] == null ){
self::$instances[ $instanceid ] = new $driver;
}
return self::$instances[ $instanceid ];
}
public function testFunction(){
//do something else
}
}
then create driver functions
class mysql extends database{
public mysql(){} // connect
public query(){} // set a query
public result(){} // load result
}
class mssql extends database{
public mysql(){} // connect
public query(){} // set a query
public result(){} // load result
}
now use it like
$database = database::getInstance( 'mysql' );
$database->query(); // works
$database->testFunction(); // works to
and further on you can use and like
$database = database::getInstance( 'mssql' );
$database->query(); // works
$database->testFunction(); // works to
I need to apologize to Froncoise for unchecking his answer as the right one.
Upvotes: 0
Reputation: 3690
nonono, this is not oop-thinking. You should google the following keywords:
When you did, put the switch statement into the factory, make the class mysql an interface named DBDriver, and use the strategy pattern in your database class.
Upvotes: 1