开发者

Help me "get" Object Orientated PHP

I'm could probably pass as a PHP developer, but I just don't "get" the object orientated side and it's high time I sorted it out.

In the code snippet I have some code I've written to pull some info from a mongoDB. I realised I've used some classes in there but I haven't constructed any - they're just what the MongoDB driver provides. In the foreach loop I have some variables that are printed out from the MongoDB. I'd like to make that foreach loop a class so that I can call something like:

print->Environment
print->Architecture

which makes it nice and clean and simple. I figure if someone can help me create a class from something I've already written it might help me "get" classes and objects. All help gratefully considered.

Consider the following:

$gethost=$_GET['q'];
try {
  // open connection to MongoDB server
  $conn = new Mongo('localhost');

  // access database开发者_高级运维
  $db = $conn->factdb;

  //authenticate
  $db->authenticate('username','password');

  // access collection
  $collection = $db->hosts;

  // define what to find
  $host = array(
        'host' => $gethost
);
  // disconnect from server
  $conn->close();
} catch (MongoConnectionException $e) {
  die('Error connecting to MongoDB server');
} catch (MongoException $e) {
  die('Error: ' . $e->getMessage());
}

 $cursor = $collection->find($host);
  foreach ($cursor as $value) {
          echo '<tr><td><b>Environment</b></td><td>'.$value['facter']['environment']['value'].'</td><td>'.date("M j Y",$value['facter']['environment']['created_at']).'</td><td>'.date("M j Y",$value['facter']['environment']['updated_at']).'</td></tr>';
  echo '<tr><td><b>FQDN</b></td><td>'.$value['facter']['fqdn']['value'].'</td><td>'.date("M j Y",$value['facter']['fqdn']['created_at']).'</td><td>'.date("M j Y",$value['facter']['fqdn']['updated_at']).'</td></tr>';
  echo '<tr><td><b>Model</b></td><td>'.$value['allocations']['model']['value'].'</td><td>'.date("M j Y",$value['allocations']['model']['created_at']).'</td><td>'.date("M j Y",$value['allocations']['model']['updated_at']).'</td></tr>';   
}


It looks to me as you have absolutely no knowledge of OOP (apart from using -> to access properties). Don't worry, the basics are not too hard to learn. You should start with the OOP chapter from The PHP Manual.

Good luck,
Alin


First of all you would probably want

$Environment->print()
$Architecture->print()

not

print->Environment
print->Architecture

Second unless we know more about Environment and Architecture data and how it is used we will not be able to create a usable class for you.

Third by looking at how objects and classes are implemented you will not "get" OOP, you should learn about Encapsulation, Inheritance, Abstraction etc.. And then worry about implementation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜