Reputation: 23
I am really new in OOP, and not a good English talker, so if my question is dumb, I am sorry. I thought I understand the oop but when I start codding with it, it works but does not feel right. the following code is my first try, I will ask my question after them. (I cut the database codes, but as I said the program works.)
// class.Post.inc
class Post {
private $_db;
private $_postId;
private $_title;
private $_creatorId;
public function __construct() {
$this->_db = Database::getInstance ()->getConnection ();
}
public function getApost($postId = 0) {
if($postId){
/* get the post data from database(including user_id) and put them in the instance variables */
$this->_postId = $row ['post_id'];
$this->_title = $row ['title'];
$this->_creatorId = $row ['user_id'];
}
}
public function getCreator() {
$creator = new User ();
return $creator->getUserObject ( $this->_creatorId );
}
public function getPostId() {
return $this->_postId;
}
public function getTitle() {
return $this->_title;
}
}
//class.User.inc
class User {
private $_db;
private $_userId;
private $_name;
public function __construct() {
$this->_db = Database::getInstance ()->getConnection ();
}
public function getUserObject($userId = null) {
if ($userId) {
/* read data from database and put them in the instance variables */
$this->_userId = $row ['user_id'];
$this->_name = $row ['name'];
return $this;
}
return false;
}
public function getUserId() {
return $this->_userId;
}
public function getName() {
return $this->_name;
}
}
//index.php
spl_autoload_register ( function ($className) {
require_once 'classes/class.' . $className . '.inc';
} );
$post = new Post ();
$post->getApost(1);
$creator = $post -> getCreator();
echo $post->getPostId () . '<br>';
echo $post->getTitle () . '<br>';
echo $creator->getName () . '<br>';
my questions:
Upvotes: 0
Views: 325
Reputation: 690
There is much that can be said about your code. I could write what you did wrong few hours, but you didn't asked for that, so I answer your questions firsts.
One piece of advice at the end: I often see new developers to reinvent a wheel, which is exactly what you are doing. There are great and feature complete libraries which saves you lot of time writing your own. For example Doctrine ORM. Or much simplier Nextras ORM. Learning curve may seem high, but I guarantee, it's worth it.
Upvotes: 1