Reputation: 159
I am following a book: "PHP and MongoDB Web Development"
Here they created a dbconnection.php script:
<?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);
}
}
I would like to use this script to list blog posts via a file called 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>
I am unsure how to proceed from here.
Upvotes: 0
Views: 642
Reputation: 3216
You have a reference to the Blogs collection; next step is to query against it:
public function __construct()
{
$this->_mongo = DBConnection::instantiate();
$this->_collection = $this->_mongo->getCollection(Blogs::COLLECTION);
$this->_blogs = $this->_collection->find();
}
This will give you a reference to the result set which you can iterate and get the individual blog documents. You'll have to then figure out how you want to make those articles accessible to your php/html.
(was using this as visual reference http://devzone.zend.com/1730/getting-started-with-mongodb-and-php/)
Upvotes: 1