Moodle: global variable $DB ( moodle_database class instance ) definition and initialization

Trabla: Moodle: global variable $DB ( moodle_database class instance ) definition and initialization


Moodle global variable $DB - tutorial screenshot 1


Global variable $DB is storage for moodle_database class instance and is used in huge amount of system scripts ( everywhere database manipulations is needed. )

Solving:

1. First time global variable $DB definition file

..\moodle\lib\setup.php

Moodle global variable $DB - tutorial screenshot 2


2. $DB global variable initialization

..\moodle\lib\dmllib.php


function setup_DB()  - Sets up global $DB moodle_database instance

Moodle global variable $DB - tutorial screenshot 3


3. If you want use moodle_database class and $DB in your project this is list of files needed to copy from moodle sources

1) ...\moodle\lib\setuplib.php
2) ...\moodle\lib\dmllib.php
3)  folder with all files  ...\moodle\lib\dml\...

Moodle global variable $DB - tutorial screenshot 4


and code

<?php


define('MOODLE_INTERNAL',true);

unset($CFG);
global $CFG;
$CFG = new stdClass();


//MySQL DB Config

/*
$CFG->dbtype    = 'mysqli';
$CFG->dblibrary = 'native';
$CFG->dbhost    = '127.0.0.1';
$CFG->dbname    = 'moodle';
$CFG->dbuser    = 'dbuser';
$CFG->dbpass    = 'dbuserpassword';
$CFG->prefix    = 'mdl_';
$CFG->dboptions = array (
  'dbpersist' => 0,
  'dbsocket' => 1,
);
*/


//PostgreSQL connection

$CFG->dbtype    = 'pgsql';
$CFG->dblibrary = 'native';
$CFG->dbhost    = 'localhost';
$CFG->dbport = '5432';
$CFG->dbname    = 'moodle';
$CFG->dbuser    = 'postgres';
$CFG->dbpass    = 'dbpassword';
$CFG->prefix    = 'mdl_';
$CFG->dboptions = array (
  'dbpersist' => 0,
  'dbsocket' => '',
);



$CFG->wwwroot   = 'hhtp://mysite.com';
$CFG->root  = '/var/www/mysite';
$CFG->dataroot  = '/var/moodledata';
$CFG->admin     = 'admin';

$CFG->libdir = $CFG->root . '/lib';

$CFG->directorypermissions = 0777;

$CFG->passwordsaltmain = '1232445$%^%$GHRHGRH';


require_once( $CFG->libdir . '/setuplib.php' );
require_once( $CFG->libdir . '/dmllib.php' );

/**
 * Database connection. Used for all access to the database.
 * @global moodle_database $DB
 * @name $DB
 */

global $DB;

// use global $CFG
setup_DB();

// your code here

No comments:

Post a Comment