나는 데이터베이스에서 게시물의 모든 데이터를 가져 오는이 클래스를 만들었습니다.다른 클래스의 클래스를 사용하는 가장 좋은 방법
class Post {
private $id;
protected $conn;
public $data;
function __construct(\mysqli $conn) {
$this->conn = $conn;
}
public function getId() {
return $this->id;
}
public function getConnection() {
return $this->conn;
}
public function getPost() {
$query1 = $this->getConnection()->query("SELECT * FROM posts WHERE id=" . $this->id);
if ($query1->num_rows == 1) {
$this->data = $query1->fetch_object();
return $this->data;
}
}
public function setId($id) {
$this->id = (int)$id;
}
}
게시물과 함께 게시물을 만든 사용자의 모든 데이터도 가져와야합니다. 이 작업을 수행하는 세 가지 방법이 있습니다.
1) Post 클래스의 User 클래스를 호출합니다. 사용자 클래스와 포스트 클래스를 확장하여
public function getPost() {
$query1 = $this->getConnection()->query("SELECT * FROM posts WHERE id=" . $this->id);
if ($query1->num_rows == 1) {
$this->data = $query1->fetch_object();
// Initiating User class
$user = new User($this->getConnection());
$user->setUserId($this->data->user_id);
$this->data->user = $user->getUserInfo();
return $this->data;
}
}
2). 사용자의 특성을 작성하고 포스트 클래스를 사용하여 사용자 클래스
public function getPost() {
$query1 = $this->getConnection()->query("SELECT * FROM posts WHERE id=" . $this->id);
if ($query1->num_rows == 1) {
$this->data = $query1->fetch_object();
// Calling methods from the User class
$this->setUserId($this->data->user_id);
$this->data->user = $this->getUserInfo();
return $this->data;
}
}
3)에서
class Post extends User {
....
그런 다음 호출 방법.
class Post {
use UserTrait;
....
그런 다음 사용자 특성이 3 사이
public function getPost() {
$query1 = $this->getConnection()->query("SELECT * FROM posts WHERE id=" . $this->id);
if ($query1->num_rows == 1) {
$this->data = $query1->fetch_object();
// Calling methods from the User trait
$this->setUserId($this->data->user_id);
$this->data->user = $this->getUserInfo();
return $this->data;
}
}
, 의존성 주입, 성능 및 코드의 청결면에서 가장 좋은 방법은 하나의 메소드를 호출?
감사합니다. @amenadiel –