Code Monkey home page Code Monkey logo

mongodb-cakephp3's Introduction

Slack

Mongodb for Cakephp3

An Mongodb datasource for CakePHP 3.5

Installing via composer

Install composer and run:

composer require hayko/mongodb dev-master

Connecting the Plugin to your application

add the following line in your config/bootstrap.php to tell your application to load the plugin:

Plugin::load('Hayko/Mongodb');

Defining a connection

Now, you need to set the connection in your config/app.php file:

 'Datasources' => [
    'default' => [
        'className' => 'Hayko\Mongodb\Database\Connection',
        'driver' => 'Hayko\Mongodb\Database\Driver\Mongodb',
        'persistent' => false,
        'host' => 'localhost',
        'port' => 27017,
        'login' => '',
        'password' => '',
        'database' => 'devmongo',
        'ssh_host' => '',
        'ssh_port' => 22,
        'ssh_user' => '',
        'ssh_password' => '',
        'ssh_pubkey_path' => '',
        'ssh_privatekey_path' => '',
        'ssh_pubkey_passphrase' => ''
    ],
],

SSH tunnel variables (starting with 'ssh_')

If you want to connect to MongoDB using a SSH tunnel, you need to set additional variables in your Datasource. Some variables are unnecessary, depending on how you intend to connect. IF you're connecting using a SSH key file, the ssh_pubkey_path and ssh_privatekey_path variables are necessary and the ssh_password variable is unnecessary. If you're connecting using a text-based password (which is not a wise idea), the reverse is true. The function needs, at minimum, ssh_host, ssh_user and one method of authentication to establish a SSH tunnel.

Models

After that, you need to load Hayko\Mongodb\ORM\Table in your tables class:

//src/Model/Table/YourTable.php

use Hayko\Mongodb\ORM\Table;

class CategoriesTable extends Table {

}

Observations

The function find() works only in the old fashion way. So, if you want to find something, you to do like the example:

$this->Categories->find('all', ['conditions' => ['name' => 'teste']]);
$this->Categories->find('all', ['conditions' => ['name LIKE' => 'teste']]);
$this->Categories->find('all', ['conditions' => ['name' => 'teste'], 'limit' => 3]);

You can also use the advanced conditions of MongoDB using the MongoDB\BSON namespace

$this->Categories->find('all', ['conditions' => [
    '_id' => new \MongoDB\BSON\ObjectId('5a7861909db0b47d605c3865'),
    'foo.bar' => new \MongoDB\BSON\Regex('^(foo|bar)?baz$', 'i')
]]);

LICENSE

The MIT License (MIT) Copyright (c) 2013

mongodb-cakephp3's People

Contributors

abdelatnova avatar delamux avatar ignaciocarre avatar issys16 avatar johnjcamilleri avatar kawaiidesune avatar ludeus avatar socialitgit avatar tiaguinho avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongodb-cakephp3's Issues

Error: Class 'Mongo' not found

So, when I went to implement this plugin, I got this error message in CakePHP...

Error: Class 'Mongo' not found 
File /var/www/llamacast/vendor/hayko/mongodb/src/Database/Connection.php 
Line: 112

I find it peculiar because on line 112 of /src/Database/Connection.php, it is a new instance of Mongodb being instantiated, not "Mongo". 😖

[InvalidArgumentException]

CakePHP ver. 3.3.3

[InvalidArgumentException]
Could not find package hayko/mongodb at any version for your minimum-stability (beta). Check the package spelling or your minimum-stability

my composer.json

{
    "name": "cakephp/app",
    "description": "CakePHP skeleton app",
    "homepage": "http://cakephp.org",
    "type": "project",
    "license": "MIT",
    "require": {
        "php": ">=5.5.9",
        "cakephp/cakephp": "3.3.*",
        "mobiledetect/mobiledetectlib": "2.*",
        "cakephp/migrations": "~1.0",
        "cakephp/plugin-installer": "*"
    },
    "require-dev": {
        "psy/psysh": "@stable",
        "cakephp/debug_kit": "~3.2",
        "cakephp/bake": "~1.1"
    },
    "suggest": {
        "markstory/asset_compress": "An asset compression plugin which provides file concatenation and a flexible filter system for preprocessing and minification.",
        "phpunit/phpunit": "Allows automated tests to be run without system-wide install.",
        "cakephp/cakephp-codesniffer": "Allows to check the code against the coding standards used in CakePHP."
    },
    "autoload": {
        "psr-4": {
            "App\\": "src"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Test\\": "tests",
            "Cake\\Test\\": "./vendor/cakephp/cakephp/tests"
        }
    },
    "scripts": {
        "post-install-cmd": "App\\Console\\Installer::postInstall",
        "post-create-project-cmd": "App\\Console\\Installer::postInstall",
        "post-autoload-dump": "Cake\\Composer\\Installer\\PluginInstaller::postAutoloadDump"
    },
    "minimum-stability": "beta",
    "prefer-stable": true
}

Installation Issue

I'm getting an error with 'composer require hayko/mongodb'

[InvalidArgumentException]
Could not find package hayko/mongodb at any version for your minimum-stability (beta). Check the package spelling or your minimum-stability

Not authorized to connect

What do I choose Auth Mechanism?

I tried default config (MONGODB-CR) to connect using Robo 3T like database manager, but it returns "Not authorized to connect". When I switch this to SCRAM-SHA-1 I get a success.

How do I change this auth mechanism in your plugin config?

Thanks!

Mongo db issue, when getting the depth level record from collections

Here i m facing the issue, when i am trying to fetch the depth level record like this:

{
    "_id" : ObjectId("589da8f4e0762a3cf5000035"),
    "user_id" : 32,
    "username" : "apurv123",
    "status" : "1",
    "c_o" : {
        "message" : "sdfsdfdsfsd",
        "date" : ISODate("2017-02-10T11:50:12.000Z")
    },
    "c_r" : {
        "message" : "",
        "date" : ""
    }
}

Class '\MongoDB' not found

Hi @tiaguinho,

I have installed PHP 5.6
Mongo 3
Cakephp 3

I am getting the following error :
Error: Class '\MongoDB' not found
File /var/www/caketest/vendor/hayko/mongodb/src/Database/Driver/Mongodb.php
Line: 152

Thanks,
Shraddha

Unable to run save query

I wanted to use this plugin with y setup of CakePHP 3.8 but I am unable to run the save data query.

This is my save method in the controller:
`$admin = $this->Admins->newEntity();

    if ($this->request->is('post')) {
        $admin = $this->Admins->patchEntity($admin, $this->request->getData());

        if ($this->Admins->save($admin)) {
            $this->Flash->success(__('The admin has been saved.'));

            $response = array('success' => true, 'msg' => "success");
        } else {
            $this->Flash->error(__('The page could not be saved. Please, try again.'));
            
            $response = array('success' => false, 'msg' =>"error");
        }

        echo json_encode($response);
        die;
    }`

Commenting this line in the save function mentioned in the "hayko\mongodb\src\ORM\Table.php"
$entity->isNew() ? RulesChecker::CREATE : RulesChecker::UPDATE
Did make it work but I am not sure if it's the right way.

The error I get is "Call to a member function select() on array".
Please help me with it ASAP.

Install instructions?

Hi!
Thanks for your plugin.
But I am wondering how to install the plugin. You suggest just to require via composer cakephp/elastic search but after that: what to do?
Enabling the plugin won´t work unless there is a plugin in vendor folder which also then should be autoloaded right?

Got error on find query

Error: Call to undefined method Hayko\Mongodb\Database\Connection::getSchemaCollection()
File E:\Xamp\htdocs\ezer\vendor\cakephp\cakephp\src\ORM\Table.php
Line: 531

Got this error when executing find query from cakephp 3.5 on mongodb 3.0.8 with mongodb driver 1.3.2 and mongo driver 1.6.16

Please help

syntax error, unexpected 'elseif' (T_ELSEIF) Error in: ROOT\vendor\hayko\mongodb\src\ORM\Document.php, line 70

Hi,
I'm using "hayko/mongodb": "dev-master" via composer in my CakePHP 3.8.6 project.

When I do a find(), I get a error 500 dump, stating:

syntax error, unexpected 'elseif' (T_ELSEIF)
ParseError
Error in: ROOT\vendor\hayko\mongodb\src\ORM\Document.php, line 70

Upon inspecting the file, it appears a closing curly-brace for the if() statement is missing.

Original code:

    public function cakefy()
    {
        $document = [];
       
        foreach ($this->_document as $field => $value) {
            $type = gettype($value);
            if ($type == 'object') {
                switch (get_class($value)) {
                    case 'MongoDB\BSON\ObjectId':
                        $document[$field] = $value->__toString();
                        break;

                    case 'MongoDB\BSON\UTCDateTime':
                        $document[$field] = $value->toDateTime();
                        break;

                    default:     
                        if ($value instanceof \MongoDB\BSON\Serializable) {                  
                                $document[$field] = $this->serializeObjects($value);
                           } else {
                            throw new Exception(get_class($value) . ' conversion not implemented.');
                         }
                // THERE NEEDS TO BE AN ADDITIONAL CURLY BRACE HERE
            } elseif ($type == 'array') {
               $document[$field] = $this->cakefy();
            } else {
                $document[$field] = $value;
            }
        }
        
        $inflector = new \Cake\Utility\Inflector();
        $entityName = '\\App\\Model\\Entity\\'.$inflector->singularize($this->_registryAlias);
        return new $entityName($document, ['markClean' => true, 'markNew' => false, 'source' => $this->_registryAlias]);
    }

If I modify the code and add in the curly brace, things get back to normal and the find() works:

    public function cakefy()
    {
        $document = [];
       
        foreach ($this->_document as $field => $value) {
            $type = gettype($value);
            if ($type == 'object') {
                switch (get_class($value)) {
                    case 'MongoDB\BSON\ObjectId':
                        $document[$field] = $value->__toString();
                        break;

                    case 'MongoDB\BSON\UTCDateTime':
                        $document[$field] = $value->toDateTime();
                        break;

                    default:     
                        if ($value instanceof \MongoDB\BSON\Serializable) {                  
                                $document[$field] = $this->serializeObjects($value);
                           } else {
                            throw new Exception(get_class($value) . ' conversion not implemented.');
                         }
				} // ADDED CLOSING BRACE
            } elseif ($type == 'array') {
               $document[$field] = $this->cakefy();
            } else {
                $document[$field] = $value;
            }
        }
        
        $inflector = new \Cake\Utility\Inflector();
        $entityName = '\\App\\Model\\Entity\\'.$inflector->singularize($this->_registryAlias);
        return new $entityName($document, ['markClean' => true, 'markNew' => false, 'source' => $this->_registryAlias]);
    }

No efficient way of counting?

I wanted an equivalent of Mongo's count command, which can return a result count without having to perform an actual find (which can be much slower). I couldn't find it in this library, so I hacked together this, added to src/ORM/Table.php:

/**
 * count documents
 *
 * @param array $options
 * @return int
 * @access public
 */
public function count($options = [])
{
    $query = new MongoFinder($this->__getCollection(), $options);
    return $query->connection()->count();
}

Not sure if I've missed something, seems like this functionality should be standard?

Installation Issue in Cakephp 3.3.10

Hi @tiaguinho, I'm getting below errors after installing in Cakephp 3.3.10

Use of undefined constant MONGODB_VERSION - assumed 'MONGODB_VERSION' [ROOT/vendor/hayko/mongodb/src/Database/Connection.php, line 109]

Error: Class '\MongoDB' not found File /Applications/XAMPP/xamppfiles/htdocs/gideon/vendor/hayko/mongodb/src/Database/Driver/Mongodb.php Line: 146

screen shot 2016-12-14 at 12 17 19 pm

Pagination not working (Cake 3.6.7)

When using CakePHP 3.6.7, the pagination function is not working. It always seems to think that the total row count for a query is 1, therefore the pagination component sets page count to 1.

I've traced this issue down to the fact that that CakePHP pagination module has the following code:

cakephp/src/Datasource/Paginator.php (188):

$count = $cleanQuery->count();
....
$pageCount = max((int)ceil($count / $limit), 1);
$page = min($page, $pageCount);

Here, query is an instance of MongoQuery. The $count seems to be always set to 1, no matter how many records there are in the database.

I was able to fix this temporarily by changing the following in src/ORM/Table.php:

public function find($type = 'all', $options = [])
    {
        $query = new MongoFinder($this->__getCollection(), $options);
        $queryWoOptions = new MongoFinder($this->__getCollection(), []);
        $method = 'find' . ucfirst($type);
        if (method_exists($query, $method)) {
            $alias = $this->getAlias();
            $mongoCursor = $query->{$method}();
            $mongoCursorWoOptions = $queryWoOptions->{$method}();
            if ($mongoCursor instanceof \MongoDB\Model\BSONDocument) {
                return (new Document($mongoCursor, $alias))->cakefy();
            } elseif (is_array($mongoCursor)) {
                return $mongoCursor;
            }
            $results = new ResultSet($mongoCursor, $alias);
            $resultsWoOptions = new ResultSet($mongoCursorWoOptions, $alias);

            if (isset($options['whitelist'])) {
                return new MongoQuery($results->toArray(), count($resultsWoOptions->toArray()));
            } else {
                return $results->toArray();
            }
        }

        throw new BadMethodCallException(
            sprintf('Unknown method "%s"', $method)
        );
    }

(Notice the addition of $queryWoOptions, $mongoCursorWoOptions, and $resultsWoOptions )

I will try to track this down more, but just wanted to open an issue to see if the developers might have an idea about this issue.

Thanks!

error on find() : Call to undefined method Hayko\Mongodb\Database\Driver\Mongodb::prepare()

Hello,

I start working on CakePHP and MongoDB, and I'm not able to use your library correctly. It might be a mistake from me but still I prefer to ask if it's a well-know error.

I'm using last CakePHP 3.5 version (3.5.17)
When I go on URL "http://127.0.0.1/MyCakePHPApp/articles/" to list articles stored in MongoDB, it display following error :
"Call to undefined method Hayko\Mongodb\Database\Driver\Mongodb::prepare()
Error
An Internal Server Error Occurred"

Here is my code :
ArticlesController.php
// src/Controller/ArticlesController.php
namespace App\Controller;
class ArticlesController extends AppController {
public function index() {
$this->loadComponent('Paginator');
$articles = $this->Paginator->paginate($this->Articles->find());
$this->set(compact('articles'));
}
}

ArticlesTable.php :
use Hayko\Mongodb\ORM\Table;
class ArticlesTable extends Table {
}

Thanks in advanced for your help
Ahmad

find by id

Olá,
Estou tendo problema com o um find filtrando pelo id.

// Esse código funciona
$user = $this->Users->find('all', ['conditions' => ['name' => "teste"]]);

// Esse código não funciona
$user = $this->Users->find('all', ['conditions' => ['_id' => "5890c6bee84c69843d8b456a"]]);

//Também tentei buscar por 'id' apenas e não '_id'
$user = $this->Users->find('all', ['conditions' => ['id' => "5890c6bee84c69843d8b456a"]]);

Não sei que estou fazendo de errado.

ORM like

Refactor driver to be more like ORM

Getting default Database connection always

i have two or more Datasources connection i wan a connection from default to other and test datasource for mongo only.
so how can i do that.
and i want to work with mysql and mongo db both.

Model, controller and query

Hi Tiago

I am trying to use your plugin but i'm facing some issues with a simple find.

For example, I have a mongo table : markers
As it is suggested in the readme, I created a MarkersTable php file, with the use Hayko\Mongodb\ORM\Table at the beginning of the file;
But what about controller ? I wrote this lines in my Markers controller :

$this->loadmodel('Markers');
$marker = $this->Markers->find_markers($keyword);

where the find_markers function is in the MarkersTable php file :

public function find_markers ($keyword) {        
        $marker = $this->Markers->find('all', ['conditions' => ['name' => $keyword]]);
        return $marker;
    }

Do i have to load in my controller the table as i said below ? ($this->loadmodel('Markers'); ) It seems not cause i have an error (Unknown method "find_markers"...Could this be caused by using Auto-Tables ?)

Thanks by advance for your help and for your work

cakephp 3 unable to migrate mongo db

plz help on this,

Exception: Could not infer database type from driver in [/var/www/nikhil3/vendor/cakephp/migrations/src/ConfigurationTrait.php, line 151]
2016-12-26 05:15:33 Error: [InvalidArgumentException] Could not infer database type from driver
Stack Trace:
#0 /var/www/nikhil3/vendor/cakephp/migrations/src/ConfigurationTrait.php(83): Migrations\Command\Migrate->getAdapterName('Hayko\Mongodb\D...')
#1 /var/www/nikhil3/vendor/robmorgan/phinx/src/Phinx/Console/Command/AbstractCommand.php(91): Migrations\Command\Migrate->getConfig()
#2 /var/www/nikhil3/vendor/cakephp/migrations/src/ConfigurationTrait.php(206): Phinx\Console\Command\AbstractCommand->bootstrap(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#3 /var/www/nikhil3/vendor/robmorgan/phinx/src/Phinx/Console/Command/Migrate.php(72): Migrations\Command\Migrate->bootstrap(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#4 /var/www/nikhil3/vendor/cakephp/migrations/src/ConfigurationTrait.php(165): Phinx\Console\Command\Migrate->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#5 /var/www/nikhil3/vendor/cakephp/migrations/src/Command/Migrate.php(58): Migrations\Command\Migrate->parentExecute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#6 /var/www/nikhil3/vendor/symfony/console/Command/Command.php(255): Migrations\Command\Migrate->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#7 /var/www/nikhil3/vendor/symfony/console/Application.php(830): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#8 /var/www/nikhil3/vendor/symfony/console/Application.php(191): Symfony\Component\Console\Application->doRunCommand(Object(Migrations\Command\Migrate), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#9 /var/www/nikhil3/vendor/symfony/console/Application.php(122): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#10 /var/www/nikhil3/vendor/cakephp/migrations/src/Shell/MigrationsShell.php(98): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput))
#11 [internal function]: Migrations\Shell\MigrationsShell->main('migrations', 'migrate')
#12 /var/www/nikhil3/vendor/cakephp/cakephp/src/Console/Shell.php(466): call_user_func_array(Array, Array)
#13 /var/www/nikhil3/vendor/cakephp/migrations/src/Shell/MigrationsShell.php(130): Cake\Console\Shell->runCommand(Array, true, Array)
#14 /var/www/nikhil3/vendor/cakephp/cakephp/src/Console/ShellDispatcher.php(227): Migrations\Shell\MigrationsShell->runCommand(Array, true, Array)
#15 /var/www/nikhil3/vendor/cakephp/cakephp/src/Console/ShellDispatcher.php(182): Cake\Console\ShellDispatcher->_dispatch(Array)
#16 /var/www/nikhil3/vendor/cakephp/cakephp/src/Console/ShellDispatcher.php(128): Cake\Console\ShellDispatcher->dispatch(Array)
#17 /var/www/nikhil3/bin/cake.php(34): Cake\Console\ShellDispatcher::run(Array)
#18 {main}

thanks in advance.

Error: Class '\MongoDB' not found

Hello Tiagu,

I implementing your plugin in cakephp3.2.12 version, but i m facing the following problem:
Error: Class '\MongoDB' not found
File D:\xampp\htdocs\sbi\vendor\hayko\mongodb\src\Database\Driver\Mongodb.php
Line: 152,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.