I'm moving my Codeigniter 3.1.4 development environment into a Docker container at the moment. When running a docker image for the first time, I would like Codeigniter to automatically create tables in the database if the database is empty rather than me having to export my current development database and then import it into the Mysql docker.
I already use the migration library during development (via the command-line) to make changes to the database schema. It sounds to me like the migration library would be perfect for this task, but I can't think of where I should call it from. E.g. - do I add some code to the end of database.php to check if the database exists and then call my migration controller somehow?
I found one way to accomplish this. In MY_Controller class, which is a class that extends CI_Controller, I check the database to see if the table ci_sessions exists. If not, I make the assumption that the database is empty and I should run the migration. Here is an example:
class MY_Controller extends CI_Controller {
function __construct() {
parent::__construct();
// If ci_sessions doesn't exist, run db migration (via command-line)
if (!$this->db->table_exists('ci_sessions')) {
$output = shell_exec("php index.php migrate");
if (strncmp($output, "Migration worked!", 17) != 0) {
exit($output);
}
}
$this->load->library ( 'session' );
$this->load->model ( 'user_model' );
}
}
Notice that I'm running the migration via a shell command. This is in order to prevent URL access to the migration controller. There might be a neater way of doing this but I haven't figured out how yet.