I'm writing a single PHP script to migrate topics from an old forums site to a new one.
- The old forums site use database "old_forums"
- Thew new forums site use database "new_forums"
- MySQL user "forums" has all privileges to both databases (I'm using 1 single user for convenience but I would not have any problems using 2 different users if required)
I have both forum hosted on the the same host - localhost
The script I have the following structure
<?php
class Forum {
//constants
const HOST = "localhost";
const DB_USER = "forums";
const DB_PASS = "forums";
...
//properties e.g. topic title, topic content
}
class OldForum extends Forum {
const DB_NAME_OLD = "old_forums";
public static function exportTopics() {
//some code
}
}
class NewForum extends Forum {
const DB_NAME_NEW = "new_forums";
public static function importTopics() {
//some code
}
}
OldForum::exportTopics();
NewForum::importTopics();
?>
I understand that I'm mixing procedural & object-oriented programming PHP (OOPP) here. I'm new to object-oriented PHP but (I have experience with Java so I'm very open to some guide to make this pure OOPP)
I would like to ultilise 1 single MySQL connection for both OldForum and NewForum class.
Where should I instantiate a mysqli object?
e.g. inside Forum class' constructor or have a new mysqli object as a property of class Forum
so that I would create a new Forum object to initiate a MySQL connection
$a_forum = new Forum();
The mysqli connection is easy enough to share between instances by creating it once in your bootstrap file and then passing it to instances that need it, e.g.
That will effectively limit the connection to one and you dont need to resort to globals inside your objects. This is called Dependency Injection and should be your prefered way of assigning dependencies to objects. It makes dependencies explicit and easy to swap out and thus benefits change, testing and maintenance.
As for your Import and Export Task, I wonder why you are doing this in PHP at all. It's apparently the same database server, so you could just do it inside your MySql instance. If you want to do it with PHP, I'd probably do something like this:
You could extract the Import and Export methods into their own Classes and then use some sort of Composite Command Pattern, but that really depends on how modular you need this to be.
Different approach would be to create some
VIEW
in the new_forums database pointing to the old_forum database. In this case, all the "views" could have, for example, "old_" prefix? Something similar to this:In such situation, you only have one connection to one database.