Quote:
Originally Posted by MattF
Initialise the database class before this one and pass it in when you initialise this class.
Code:
$blogpost = new BlogPost($db);
class BlogPost
{
private $database = '';
function __construct($database)
{
$this->database = $database;
}
}
|
This is how I'd do it as well. I try to limit object coupling as much as possible, so passing a parameter in makes the most sense.
What I can suggest (when you're OO skill is a little more advanced) is to interface whatever is being passed in. This allows you to guarentee (minus a bug, I won't go into that) that all methods are available in the given class. This only works for a more pure OO approach, where the parameter is also an object:
PHP Code:
interface IStorage
{
public function connect(....);
public function select(....);
//....
}
class XMLFileDriver implements IStorage
{
public function connect(...)
{
// Open a file, maybe a domdocument, whatever
}
public function select(...)
{
// yeah, actually the dom would be great for selections
}
}
class BlogPost
{
private $database = '';
function __construct(IStorage $database)
{
$this->database = $database;
$this->database->connect(...);
}
public function getBlogPost($maybeAnIDHere)
{
$qry = $this->database->select(array('*'), 'Post', $maybeAnIDHere);
$sResult = '';
if ($qry)
{
$sResult = $this->database->fetch($qry); // Assume we have a fetch
}
else
{
$sResult = 'No match';
}
return $sResult;
}
}
$blogPost = new BlogPost(new XMLFileDriver('/path/to/XML.xml'));
print $blogPost->getBlogPost(1);
Does that make sense? Its a little trickier to follow, but in the above we made a storage device, using an XML file for this example, selected from it and returned the blogPost. Now the above is a completely incomplete representation, its mearly to show the idea of datatyping (or TypeHinting in PHP) to ensure that the IStorage interface has the connect, select and fetch methods. It doesn't matter at this point what the IStorage represents, it can be flat, XML, databases, stdin, whatever you want.
Also, I thought this was refering to nested classes when I read the title:
PHP Code:
class A
{
class B
{
}
}
PHP does not support nested or inner classes.