Skip to content

Serialization

Eldar Shahmaliyev edited this page Jan 27, 2025 · 1 revision

The SDK provides the ability to serialize and deserialize objects, making it easy to save and reuse data across sessions or for other purposes. Serialization converts objects into a format that can be saved to a file or database, while deserialization restores the object to its original state.

Serializing Objects

Any response or lexicon object can be serialized into a JSON string:

use Atproto\Client;
use Atproto\Responses\Com\Atproto\Repo\CreateRecordResponse;

// Create and send a record
$client = new Client();
$response = bskyFacade($client)->createRecord()
    ->record($post) // Add the record content
    ->repo($client->authenticated()->did())
    ->collection($post->nsid())
    ->send();

// Serialize the response
$serialized = json_encode($response);
file_put_contents('response.json', $serialized);

echo "Serialized response saved successfully.";

Deserializing Objects

Restore a previously serialized object to reuse it:

use Atproto\Responses\Com\Atproto\Repo\CreateRecordResponse;

// Load the serialized JSON
$serialized = file_get_contents('response.json');

// Deserialize the JSON into an object
$response = new CreateRecordResponse(json_decode($serialized, true));

// Access the deserialized data
echo $response->uri(); // Output the URI of the created record

Use Case: Saving Sessions

This serialization functionality is particularly useful for saving and restoring sessions. By serializing the session data, you can avoid re-authenticating on every request.

use Atproto\Responses\Com\Atproto\Server\CreateSessionResponse;

// Save session data
$session = $client->authenticated();
file_put_contents('session.json', json_encode($session));

// Restore session data
$sessionData = file_get_contents('session.json');
$restoredSession = new CreateSessionResponse(json_decode($sessionData, true));

$client->authenticate($identifier, $password, $restoredSession);
  • 🏠 Home
    Introduction to the SDK and its features

  • 🚀 Quick Start
    Get started quickly with the basics of using the Bluesky SDK

  • ⚙️ Installation
    Step-by-step guide to installing the SDK

  • 🛠️ Architecture Overview
    Learn about the SDK's structure and design principles

  • 📖 BskyFacade
    Simplify API interactions with the facade

  • 💾 Serialization
    Serialize and deserialize data effectively

  • 🔄 Session Management
    Manage authentication and session reuse

  • 🧹 Casting
    Explore type-safe response casting in the SDK

  • 💡 Examples
    Practical usage examples for various features

Clone this wiki locally