MongoDB 和 CodeIgniter

发布于 2024-08-21 09:53:04 字数 1536 浏览 7 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

赠佳期 2024-08-28 09:53:04

我不确定它是否是“CodeIgniter 方式”,但我创建了一个 CodeIgniter 库,它使用一个额外的属性来扩展 Mongo 类来存储当前的数据库连接。

这是我的项目中的相关代码文件。

config/mongo.php

$config['mongo_server'] = null;
$config['mongo_dbname'] = 'mydb';

libraries/Mongo.php

class CI_Mongo extends Mongo
{
    var $db;

    function CI_Mongo()
    {   
        // Fetch CodeIgniter instance
        $ci = get_instance();
        // Load Mongo configuration file
        $ci->load->config('mongo');

        // Fetch Mongo server and database configuration
        $server = $ci->config->item('mongo_server');
        $dbname = $ci->config->item('mongo_dbname');

        // Initialise Mongo
        if ($server)
        {
            parent::__construct($server);
        }
        else
        {
            parent::__construct();
        }
        $this->db = $this->$dbname;
    }
}

和示例控制器

controllers/posts.php

class Posts extends Controller
{
    function Posts()
    {
        parent::Controller();
    }

    function index()
    {
        $posts = $this->mongo->db->posts->find();

        foreach ($posts as $id => $post)
        {
            var_dump($id);
            var_dump($post);
        }
    }

    function create()
    {
        $post = array('title' => 'Test post');
        $this->mongo->db->posts->insert($post);
        var_dump($post);
    }
}

I'm not sure if its the "CodeIgniter way" but I created a CodeIgniter library that extends the Mongo class with an extra property to store the current database connection.

Here are the relevant code files from my project.

config/mongo.php

$config['mongo_server'] = null;
$config['mongo_dbname'] = 'mydb';

libraries/Mongo.php

class CI_Mongo extends Mongo
{
    var $db;

    function CI_Mongo()
    {   
        // Fetch CodeIgniter instance
        $ci = get_instance();
        // Load Mongo configuration file
        $ci->load->config('mongo');

        // Fetch Mongo server and database configuration
        $server = $ci->config->item('mongo_server');
        $dbname = $ci->config->item('mongo_dbname');

        // Initialise Mongo
        if ($server)
        {
            parent::__construct($server);
        }
        else
        {
            parent::__construct();
        }
        $this->db = $this->$dbname;
    }
}

And a sample controller

controllers/posts.php

class Posts extends Controller
{
    function Posts()
    {
        parent::Controller();
    }

    function index()
    {
        $posts = $this->mongo->db->posts->find();

        foreach ($posts as $id => $post)
        {
            var_dump($id);
            var_dump($post);
        }
    }

    function create()
    {
        $post = array('title' => 'Test post');
        $this->mongo->db->posts->insert($post);
        var_dump($post);
    }
}
抚笙 2024-08-28 09:53:04

MongoDB 在 CodeIgniter 社区中得到了很好的支持,请花点时间深入了解 :p

MongoDB is very well supported within CodeIgniter community, take the time and dive in :p

恏ㄋ傷疤忘ㄋ疼 2024-08-28 09:53:04

我喜欢 Stephen Curran 的示例,因为它很简单,并且允许与 Mongo 接口,而无需在 Php 中编写太多功能,我倾向于有时会发现巨大的抽象类对于我所追求的东西来说有点多。

我扩展了他的示例以包括数据库身份验证。转到此处: http://www.mongodb.org/display/DOCS/Security +and+Authentication 要了解 mongo 身份验证,请不要忘记为您要连接的 Mongo 服务器启用身份验证。

我还将旧式构造函数更改为 __construct 并正在处理 Mongo 连接异常,因为它们可以泄露您的用户名和密码。

配置/mongo.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$config['mongo_server'] = 'localhost';
$config['mongo_dbname'] = 'my_mongo_db';
$config['mongo_username'] = 'mongo_user';
$config['mongo_password'] = 'password1234';

/* End of file mongo.php */

库/Mongo.php

<?php

class CI_Mongo extends Mongo{

    protected $db;

    function __construct()
    {   
        // Fetch CodeIgniter instance
        $ci = get_instance();
        // Load Mongo configuration file
        $ci->load->config('mongo');

        // Fetch Mongo server and database configuration
        $server = $ci->config->item('mongo_server');
        $username = $ci->config->item('mongo_username');
        $password = $ci->config->item('mongo_password');
        $dbname = $ci->config->item('mongo_dbname');

        // Initialise Mongo - Authentication required
        try{
            parent::__construct("mongodb://$username:$password@$server/$dbname");
            $this->db = $this->$dbname;
        }catch(MongoConnectionException $e){
            //Don't show Mongo Exceptions as they can contain authentication info
            $_error =& load_class('Exceptions', 'core');
            exit($_error->show_error('MongoDB Connection Error', 'A MongoDB error occured while trying to connect to the database!', 'error_db'));           
        }catch(Exception $e){
            $_error =& load_class('Exceptions', 'core');
            exit($_error->show_error('MongoDB Error',$e->getMessage(), 'error_db'));           
        }
    }
}

I like Stephen Curran's example as it is simple and allows an interface to Mongo without too much functionality written within Php, I tend to find huge abstraction clases a bit much at times for what I am after.

I have extended his example to include database authentication. Go here: http://www.mongodb.org/display/DOCS/Security+and+Authentication to read about mongo authentication, don't forget to enable authentication for the Mongo Server you are connecting to.

I have also changed the old style constructor function to be __construct and am handling Mongo Connection Exceptions as they can reveal your username and password.

config/mongo.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$config['mongo_server'] = 'localhost';
$config['mongo_dbname'] = 'my_mongo_db';
$config['mongo_username'] = 'mongo_user';
$config['mongo_password'] = 'password1234';

/* End of file mongo.php */

libraries/Mongo.php

<?php

class CI_Mongo extends Mongo{

    protected $db;

    function __construct()
    {   
        // Fetch CodeIgniter instance
        $ci = get_instance();
        // Load Mongo configuration file
        $ci->load->config('mongo');

        // Fetch Mongo server and database configuration
        $server = $ci->config->item('mongo_server');
        $username = $ci->config->item('mongo_username');
        $password = $ci->config->item('mongo_password');
        $dbname = $ci->config->item('mongo_dbname');

        // Initialise Mongo - Authentication required
        try{
            parent::__construct("mongodb://$username:$password@$server/$dbname");
            $this->db = $this->$dbname;
        }catch(MongoConnectionException $e){
            //Don't show Mongo Exceptions as they can contain authentication info
            $_error =& load_class('Exceptions', 'core');
            exit($_error->show_error('MongoDB Connection Error', 'A MongoDB error occured while trying to connect to the database!', 'error_db'));           
        }catch(Exception $e){
            $_error =& load_class('Exceptions', 'core');
            exit($_error->show_error('MongoDB Error',$e->getMessage(), 'error_db'));           
        }
    }
}
春风十里 2024-08-28 09:53:04

在 CodeIgniter 中使用 MongoDB 与在其他地方使用 MongoDB 没有太大区别。

您可以组合一个 MongoDB 库,该库将在构造函数中连接并存储 $this->conn 以便稍后在方法中使用。

然后要么直接使用控制器中的 conn 属性,要么在 MongoDB 库中创建一些方法来为您执行此操作。

请查看此处,了解使用 MongoDB 的简单 PHP 教程。

我很乐意为此创建一个库,但它是有代价的。 :-p

Working with MongoDB in CodeIgniter wouldn't be much different than working with it anywhere else.

You could knock together a MongoDB library that would connect in the constructor and store $this->conn to be used in methods later on.

then either work directly with the conn property in your controllers or create a few methods in your MongoDB library to do this for you.

Take a look here to see the plain PHP tutorial for working with MongoDB.

I'd happily create you a library for this but it would come with a price. :-p

魔法少女 2024-08-28 09:53:04

我正在使用带有 CI 的 MongoDB,并提出了以下建议。它对我有用,但我确信它可以进行一些调整。我稍后会担心调整它,但现在它已经达到了我想要的效果。

我创建了一个名为“database_conn.php”的模型,

class Database_Conn extends Model {

    function _connect() {
        $m = new Mongo();

        $db = $m->selectDB( "YOUR DATABASE NAME" );
        return $db;
    }
}

然后,如果我需要连接到我的模型中的集合。

$collection = Database_Conn::_connect()->selectCollection( "COLLECTION NAME" );

I'm using MongoDB w/ CI and came up with the following. It works for me, but I'm sure it can be tweaked somewhat. I'll worry about tweaking it later but right now it does what I want.

I created a model called "database_conn.php"

class Database_Conn extends Model {

    function _connect() {
        $m = new Mongo();

        $db = $m->selectDB( "YOUR DATABASE NAME" );
        return $db;
    }
}

Then, if I need to connect to a collection from my models.

$collection = Database_Conn::_connect()->selectCollection( "COLLECTION NAME" );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文