I'm new to Yii, and experimenting with yii2's createCommand(), for this I've to create a new instance of the class yii\db\connection,
Here is an action in my controller,
public function actionDues($student_id){
$connection = new \yii\db\Connection([
'dsn' => 'mysql:host=localhost;dbname=db_school',
'username' => 'root',
'password' => '',
'enableSchemaCache' => true,
]);
$sql = 'select * from group_fees where group_id in (select group_id from group_subscriptions where subscriber_id='.$student_id.')';
$command = $connection->createCommand($sql)->queryAll();
}
Am I right in thinking that there must be a connection instance already loaded, which I can use, instead of creating a new instance of the yii\db\connection class as above?
The db connection istance is normally create during the application boostrap phase by yii2 for this you set the related param in config/main.php or main-local (yii2-advanced template) or config/web.php -> db.php (in yii2 basic template)
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=your_host;dbname=your_dbdame;port=3306',
'username' => 'root',
'password' => 'your_pwd',
'charset' => 'utf8',
'enableSchemaCache' => true,
],
and with this configuration you can use the db connection this way
$sql = "select a,b, from ..... your sql command';
Yii::$app->db->createCommand($sql)->execute()
Autoloading mechanism is not what you are thinking, Think about it as Loading a class automatically on demand or when you require it.
If you were not using autoloading you would be including every file which has class definition in your index file. Now consider a framework like Yii has huge number of classes say some thousand libraries, now including all these class files on index page would cost thousands of lines of code which only including class definitions, also this act will make index script slow.
What autoloading does is when you try to instantiate a class by using fully qualified namespace, it actually converts backslash in namespace to forward slash and look for the class in that path and include it on your index file. For example in your code you used \yii\db\Connection
so autoloading function will make it /yii/db/Connection
and will look for the class Connection
in the /yii/db/Connection
path and then will include it on your index file. So this act make the script run faster and no need to write that thousand line of code.
You can read more about namespaces and about autoloading