Switching databases between development and deployment - yii2-advanced-app

Hy guys,
how to switch probably databases from development to deployment in yii2-advanced!
I use following config-file:
.
.
.
'db_developpment' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2_widget',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'db_deployment' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host="http:/tklustig.ddns.net";dbname=yii2_widget',
'username' => 'my_name',
'password' => 'my_password',
'charset' => 'utf8',
],
.
.
.
I suppose, it's necessary to code an IF-statement in order to difference between developpment and deployment settings.
How to code this IF-statement correctly?

Do you really need two DB connections at the same time? It makes everything more complicated.
The preferred way is to keep several environments configuration. Each environment uses it's own DB connection setup.
See the Yii 2 Advanced Template Project docs about this.
Basically you prepare two different configs:
/environments/dev/common/config/main-local.php
/environments/prod/common/config/main-local.php
Inside there is db component configured for each environment. When deploying app you run console command init where you choose environment to be initialized so the proper main-local.php file is copied to folder and now db component uses the environment-based configuration so you just use one active connection.

Related

Connecting DigitalOcean Managed MongoDB to Laravel (connection error calling ismaster)

I'm attempting to set up Laravel with the Managed MongoDB provided by DigitalOcean, though for some reason the database is not connecting.
I've hit a wall and I think it's something to do with authSource, but can't replicate it via cli otherwise...
.env file
MONGO_DSN="mongodb+srv://username:password#digitaloceanhostname/databasename?authSource=admin"
MONGO_DATABASE="databasename"
MONGO_USER="username"
MONGO_PASSWORD="password"
MONGO_TLS=true
MONGO_TLS_CERT="./mongo-db-cert.crt"
config/database.php
'connectionmethod' => [
'driver' => 'mongodb',
'dsn' => env('MONGO_DSN'),
'database' => env('MONGO_DATABASE', ''),
'username' => env('MONGO_USER', ''),
'password' => env('MONGO_PASSWORD', ''),
'options' => [
'tls' => (bool) env('MONGO_TLS', false),
'tlsCAFile' => env('MONGO_TLS_CERT', null),
'authSource' => 'admin',
'db' => 'admin',
'database' => 'admin',
],
],
The above causes the following error:
ERROR: No suitable servers found (`serverSelectionTryOnce` set): [connection error calling ismaster on 'digitaloceanhostname'
(MongoDB\\Driver\\Exception\\ConnectionTimeoutException(code: 13053): No suitable servers found (`serverSelectionTryOnce` set): [connection error calling ismaster on 'digitaloceanhostname:27017']
However, when using the CLI to call ismaster, it works:
# mongo "mongodb+srv://MONGO_USER:MONGO_PASSWORD#digitaloceanhostname/MONGO_DATABASE?authSource=admin" --eval 'printjson(db.runCommand({"isMaster": 1}))' --ssl --sslCAFile ./mongo-db-cert.crt
Running it without the ?authSource=admin causes an authentication error, which is making me think the connection error from laravel is the same thing.
Environment:
# mongo --version
MongoDB shell version v3.6.8
# apt list --installed | grep php | grep mongo
php7.4-mongodb/focal,now 1.9.0+1.7.5-6+ubuntu20.04.1+deb.sury.org+1 amd64 [installed]
# php artisan --version
Laravel Framework 5.8.38
I'm probably missing something obvious, but after looking at this all day any input is appreciated!
The solution was to provide the FULL PATH to the certificate.

Using Jenssegers MongoDB with Slim and Capsule

I am using the Slim 4 framework along with Jenssegers MongoDB library and Capsule (Illuminate\Database from Laravel). I have got the MongoDB extension installed on my Linux server and everything seems ok connection wise, but I cannot seem to insert data into the database or get anything from it. I have tried with the query builder and Eloquent. My code with query builder example is below.
use Illuminate\Database\Capsule\Manager as Capsule;
$capsule = new Capsule;
$capsule->getDatabaseManager()->extend('mongodb', function($config, $name) {
$config['name'] = $name;
return new \Jenssegers\Mongodb\Connection($config);
});
$capsule->addConnection([
'host' => '127.0.0.1',
'port' => 27017,
'database' => 'testing',
'username' => '',
'password' => '',
], 'mongodb');
// Set the event dispatcher used by Eloquent models... (optional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));
// Make this Capsule instance available globally via static methods... (optional)
$capsule->setAsGlobal();
// Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
$capsule->bootEloquent();
$capsule->connection('mongodb')->collection('testing')->insert([
'test1'=>'hello',
'test2'=>'world',
]);
The database and collection exist as I can see them in Compass. Can anyone see where I'm going wrong with the code or is it a configuration issue?
There were two problems, one was the driver missing as you point out, but the other was the fact my PHP is running in Linux using Vagrant and it was pointing to localhost, but the MongoDB server is running on the Windows machine and not Linux. Thanks.

Lumen and MongoDB?

Is it somehow possible to include the mongodb connection settings into a lumen framework. As from what I saw the config/database.php is loaded internally in the lumen package. Is there a way to extend it somehow to include the mongodb connection settings?
We're actually using Lumen, Laravel, Mongo, and MySQL in one giant project so I can help you through this one. Assuming you want to use MongoDB with eloquent instead of with the raw MongoClient. You can find the library I'm using from jenssegers here.
Install MongoDB Extension
Firstly you'll need to install the dependencies for PHP to interact with mongo. The specifics for installing the mongo extension can be found on the PHP documentation.
After that you'll have to edit the php.ini files for the platforms (apache/cli/nginx) to load the extension. I added the following before Module Settings
extension=mongo.so
It goes without saying you need to restart apache/nginx after changing the configuration.
Configuring Lumen
In your root lumen folder you can add it to your requirements with the following command.
composer require jenssegers/mongodb
From there you'll need to also load the MongodbServiceProvider before Facades or Eloquent is initialized.
$app->register(Jenssegers\Mongodb\MongodbServiceProvider::class);
$app->withFacades();
$app->withEloquent();
For simplicity of organizing configuration I also created a config folder and a database.php config file. Since Lumen doesn't try to autoload or search this directory we have to tell it to load this config. I put the following line right before the loading the application routes.
$app->configure('database');
In database.php the mongodb driver requires a specific structure. I've included mysql in here as I use both, but if you're using mongo exclusively you can change default to mongodb and remove the mysql config.
return [
'default' => 'mysql',
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', ''),
'username' => env('DB_USERNAME', ''),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'mongodb' => array(
'driver' => 'mongodb',
'host' => env('MONGODB_HOST', 'localhost'),
'port' => env('MONGODB_PORT', 27017),
'username' => env('MONGODB_USERNAME', ''),
'password' => env('MONGODB_PASSWORD', ''),
'database' => env('MONGODB_DATABASE', ''),
'options' => array(
'db' => env('MONGODB_AUTHDATABASE', '') //Sets the auth DB
)
),
],
];
With the configuration out of the way you can now create a model, as of writing this to create a model for mongo (check the github page) you can use the following as a base. You can ignore the $connection variable if mongo is your default driver.
<?php
namespace App;
use Jenssegers\Mongodb\Model as Eloquent;
class Example extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'example';
protected $primaryKey = '_id';
}
There you go, you should be able to interact with mongo normally, for the specifics of the driver check out the github page for documentation on it.
If this answer helped you could you mark it as the answer?
2016 (Update)
There is now a simple Doctrine MongoDB ODM Provider for the Lumen PHP framework.
composer require nordsoftware/lumen-doctrine-mongodb-odm
GitHub Source Code
Warning
jenssegers/mongodb is a Driver sitting on top of Illumante's Eloquent ORM.
Think of it: Eloquent ORM is primary made for SQL. And let's cut with the chase: The package is the reinvention of the wheel - as a side effect, major mongodb features are not supported. Besides that, the package is unstable and unmaintained.
Be aware, jenssegers/mongodb will vent your anger and frustration:
Just a change in #Sieabah user:
instead: extension=mongo.so
choose: extension=mongodb.so

Configure Dancer from environment variables?

I'm new to Dancer, but I'm trying to configure it to work within a Docker container. As a result, I need to pick up my database settings from the environment.
In my case, I have DB_PORT_3306_TCP_ADDR, and DB_PORT_3306_TCP_PORT coming from Docker. Unfortunately, the Dancer::Plugin::Database module is erroring before I can change the database to use those variables.
use Dancer ':syntax';
use Dancer::Plugin::Database;
if ($ENV{DB_PORT_3306_TCP}) {## Connected via docker.
database->({
driver => 'mysql',
username => 'username',
password => 'password',
host => $ENV{DB_PORT_3306_TCP_ADDR},
port => $ENV{DB_PORT_3306_TCP_PORT},
database => $ENV{DB_ENV_MYSQL_DATABASE},
});
}
So the question is, is there a good way to configure Dancer from environment variables, instead of through static YAML?
See Runtime Configuration in the Dancer::Plugin::Database docs:
You can pass a hashref to the database() keyword to provide configuration details to override any in the config file at runtime if desired, for instance:
my $dbh = database({ driver => 'SQLite', database => $filename });
You're adding a ->, which causes an error. The following should work:
use Dancer ':syntax';
use Dancer::Plugin::Database;
if ($ENV{DB_PORT_3306_TCP}) {## Connected via docker.
database({
driver => 'mysql',
username => 'username',
password => 'password',
host => $ENV{DB_PORT_3306_TCP_ADDR},
port => $ENV{DB_PORT_3306_TCP_PORT},
database => $ENV{DB_ENV_MYSQL_DATABASE},
});
}
At the beginning of your lib/myapp.pm, after module loading, add :
setting('plugins')->{'Database'}->{'host'}='postgres';
setting('plugins')->{'Database'}->{'database'}=$ENV{POSTGRES_DB};
setting('plugins')->{'Database'}->{'username'}=$ENV{POSTGRES_USER};
setting('plugins')->{'Database'}->{'password'}=$ENV{POSTGRES_PASSWORD};
and keep static config (Driver, port) in config.yml

Cakephp 2.0 Mongodb Plugin not loading

I am trying to change my database over to Mongodb. I have Mongo loaded and working from the shell. Now I am trying to get cakephp 2.0 to connect to the database. I have downloaded and installed ichiaway's drive into the app/plugin directory as Mongodb. I have included the line
CakePlugin::load('Mongodb');
in my bootstrap.php file. I have changed my database.php file to
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'mongodb.mongodbSource',
'host' => 'localhost',
'database' => 'service4u',
'port' => 27017
);
The database works as a service right now and I can start the mongo shell and work with the database just fine but when I try and load a page from my app I get the following error.
Missing Plugin
Error: The application is trying to load a file from the mongodb plugin
Error: Make sure your plugin mongodb is in the app\Plugin directory and was loaded
<?php
CakePlugin::load('mongodb');
Loading all plugins: If you wish to load all plugins at once, use the following line in your app\Config\bootstrap.php file
CakePlugin::loadAll();
I am at a loss now on what to do. I have tried putting the files in different folders inside the Mongodb folder in the plugin folder but nothing I do helps. Any insight would be helpful. Thanks.
Was able to find the answer. The only thing I had wrong was in my database.php file the datasource should be camelCase. I had lowercase m's, changed them to M and it worked.
Found the answer here
CakePHP 2 can not find plugin
Make sure downlaod file more then 2.5.if not please
Download mongoDB plugin for cake php.
just download and put he all file on app/plugin/Mongodb.
set database in database.php
public $default = array(
'datasource' => 'Mongodb.MongodbSource',
'host' => 'localhost',
'database' => 'blog',
'port' => 27017,
'prefix' => '',
'persistent' => 'true',
);
public $test = array(
'datasource' => 'Mongodb.MongodbSource',
'database' => 'test_mongo',
'host' => 'localhost',
'port' => 27017,
);
and add blow code on bootstrap.php
CakePlugin::load('Mongodb');