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
Related
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.
Steps to install laravel/scout on Lumen framework (there are some additional steps that you need to do to make it work with lumen opposed to Laravel)
First install laravel
composer require laravel/scout
Register the service provider in the bootstrap/app.php in the provider section
$app->register(Laravel\Scout\ScoutServiceProvider::class);
Copy the configuration file (you may be able to do it with composer php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider" , I wasn't)
cp vendor/laravel/scout/config/scout.php config/scout.php
Ask lumen to load the configuration file, adding this line to boostrap/app.php
$app->configure('scout');
Install laravel mysql mysql driver
composer require yab/laravel-scout-mysql-driver
Change the driver setting in config/scout.php
'driver' => env('SCOUT_DRIVER', 'mysql'),
Append this to config/scout.php
'mysql' => [
'mode' => 'NATURAL_LANGUAGE',
'model_directories' => [app_path()],
'min_search_length' => 0,
'min_fulltext_search_length' => 4,
'min_fulltext_search_fallback' => 'LIKE',
'query_expansion' => false
]
run the scout index if plan to use in NATURAL_LANGUAGE or BOOLEAN
php artisan scout:mysql-index
Use like this
Model::search(searchString)->get();
You can also add other conditions
Model::search(searchString)->where(...)->get()
According to the above answer,this line:
'driver' => env('SCOUT_DRIVER', 'mysql'),
cause an error which was "Driver [mysql] not supported".
For solving the problem use "database" instead of "mysql" as a driver.
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.
I installed Yii 2 advanced template. "yii migrate" command in CMD works perfectly with the default MySQL database, it populates the database with the tables migration and user as expected (see step 3 explained here: https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/start-installation.md)
But "yii migrate" doesn't work with the postgresql database. It produces following error message:
What's wrong, or what is missing? Data tables can be read by the Yii 2 framework if I create them manually (already tested), but migrate command doesn't want to work.
The required pdo extensions for postgresql are out-commented in the php.ini file. The web page requirements.php shows "passed" (no errors or warnings) for PDO PostgreSQL extension.
My db connection configuration in common/config/main-local.php:
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'tablePrefix' => 'tbl_',
'dsn' => 'pgsql:host=localhost;port=5432;dbname=mytestdb',
'username' => 'postgres',
'password' => 'tuparnix',
'charset' => 'utf8',
// see: http://stackoverflow.com/questions/26436024/how-to-set-default-schema-in-yii2
'schemaMap' => [
'pgsql'=> [
'class'=>'yii\db\pgsql\Schema',
'defaultSchema' => 'public' //specify your schema here
],
], // PostgreSQL
],
Your command line php and your web server php is a different php.
You need to out-comment your postgres driver in command-line php.ini.
Please run these in command line for more info (I'm not sure what is windows version of these command, please chk)
which php
php -i
I have the same problem in Windows but not Linux. Perhaps, that come from driver php_pdo_pgsql + libpq.dll.
Which version you have in your phpinfo (), Postgresql 8.3.3 (windows) or 9.2.1 (linux) that would not be compatible. Looking from this side.
What is the server you are using on Windows? (xampp, easyphp, WampServer) and what version of php (5.4, 5.5, 5.6 ...).
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');