0

我正在关注一本书:“PHP 和 MongoDB Web 开发”

他们在这里创建了一个 dbconnection.php 脚本:

<?php

class DBConnection
{
    const HOST   = 'localhost';
    const PORT   = 27017;
    const DBNAME = 'myblogsite';

    private static $instance;

    public $connection;    
    public $database;

    private function __construct()
    {
        $connectionString = sprintf('mongodb://%s:%d', DBConnection::HOST, DBConnection::PORT);

        try {

            $this->connection = new Mongo($connectionString);
            $this->database = $this->connection->selectDB(DBConnection::DBNAME);

        } catch (MongoConnectionException $e) {
            throw $e;
        }
    }

    static public function instantiate()
    {
        if (!isset(self::$instance)) {
            $class = __CLASS__;
            self::$instance = new $class;
        }

        return self::$instance;
    }

    public function getCollection($name)
    {
        return $this->database->selectCollection($name);
    }
}

我想使用这个脚本通过一个名为 blogs.php 的文件列出博客文章:

<?php

require_once('dbconnection.php');

class Blogs
{
    const COLLECTION = 'articles';

    private $_mongo;
    private $_collection;
    private $_blogs;

    public function __construct()
    {
        $this->_mongo = DBConnection::instantiate();
        $this->_collection = $this->_mongo->getCollection(Blogs::COLLECTION);
    }


}

$blogs = new Blogs();


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <link rel="stylesheet" href="style.css" /> 
    <title>My Blog Site</title>
    </head>

          <body>
              <div id="contentarea">
                  <div id="innercontentarea">
                      <h1>My Blogs</h1>

                      <?php while ($blogs->hasNext()):
                        $article = $blogs->getNext(); ?>
                        <h2><?php echo $article['title']; ?></h2>
                        <p><?php echo substr($article['content'], 0, 200).'...'; ?></p>
                        <a href="blog.php?id=<?php echo $article['_id']; ?>">Read more</a>
                      <?php endwhile; ?>
                  </div>
              </div>
          </body>
</html>

我不确定如何从这里开始。

4

1 回答 1

1

你有一个博客集合的引用;下一步是查询它:

public function __construct()
{
    $this->_mongo = DBConnection::instantiate();
    $this->_collection = $this->_mongo->getCollection(Blogs::COLLECTION);
    $this->_blogs = $this->_collection->find();
}

这将为您提供对结果集的引用,您可以对其进行迭代并获取各个博客文档。然后,您必须弄清楚您希望如何使这些文章可以访问您的 php/html。

(将其用作视觉参考http://devzone.zend.com/1730/getting-started-with-mongodb-and-php/

于 2012-05-27T02:01:31.163 回答