라이브러리
[PHP] MongoDBBSONPersistable::bsonSerialize - BSON으로 직렬화할 배열이나 문서를 제공합니다.
MongoDBBSONPersistable::bsonSerialize
`MongoDBBSONPersistable`은 MongoDB와 연동하기 위해 사용되는 PHP 클래스입니다. 이 클래스는 MongoDB의 BSON (Binary Serialized Object Notation) 형식을 serialize하는 데 사용됩니다. `bsonSerialize` 메서드는 이 클래스의 핵심 메서드 중 하나로, 객체를 BSON 형식으로 serialize하는 데 사용됩니다.
bsonSerialize 메서드
`bsonSerialize` 메서드는 객체의 속성을 BSON 형식으로 serialize합니다. 이 메서드는 객체의 속성을 검사하고, BSON 형식으로 serialize할 수 있는 속성을 BSON 형식으로 변환합니다.
예제
다음 예제는 `MongoDBBSONPersistable` 클래스를 사용하여 객체를 BSON 형식으로 serialize하는 방법을 보여줍니다.
#hostingforum.kr
php
use MongoDBBSONUTCDateTime;
use MongoDBBSONObjectId;
class User implements MongoDBBSONPersistable
{
private $id;
private $name;
private $email;
private $createdAt;
public function __construct($name, $email)
{
$this->name = $name;
$this->email = $email;
$this->createdAt = new UTCDateTime();
}
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
public function getCreatedAt()
{
return $this->createdAt;
}
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
public function bsonSerialize()
{
return [
'_id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'createdAt' => $this->createdAt,
];
}
}
$user = new User('John Doe', 'john.doe@example.com');
$user->setId(new ObjectId());
$serializedUser = $user->bsonSerialize();
print_r($serializedUser);
이 예제에서는 `User` 클래스를 정의하고, `bsonSerialize` 메서드를 구현하여 객체를 BSON 형식으로 serialize합니다. `bsonSerialize` 메서드는 객체의 속성을 BSON 형식으로 serialize하고, `_id` 속성을 `ObjectId` 형식으로 serialize합니다.
결과
다음은 예제의 결과입니다.
#hostingforum.kr
php
Array
(
[_id] => MongoDBBSONObjectId Object
(
[oid] => 60a2a8b0f5e6c7d8e9f0a1b2
)
[name] => John Doe
[email] => john.doe@example.com
[createdAt] => MongoDBBSONUTCDateTime Object
(
[milliseconds] => 1643723400000
)
)
이 예제는 `MongoDBBSONPersistable` 클래스를 사용하여 객체를 BSON 형식으로 serialize하는 방법을 보여줍니다. `bsonSerialize` 메서드는 객체의 속성을 BSON 형식으로 serialize하고, `_id` 속성을 `ObjectId` 형식으로 serialize합니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.