PHP code example of feedple / feedple-sdk

1. Go to this page and download the library: Download feedple/feedple-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

feedple / feedple-sdk example snippets



Feedple\Sdk\FeedpleSDK;
use Feedple\Sdk\Core\Identity;

// 1. Create a PDO connection to your database
$pdo = new PDO(
    'mysql:host=localhost;dbname=myapp;charset=utf8mb4',
    'db_user',
    'db_pass',
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

// 2. Define which tables Feedple can access
$identity = new Identity(
    name:      'production',
    allTables: true,           // expose every table, or…
    // allowedTables: ['users', 'orders', 'products'],  // …restrict to specific tables
);

// 3. Initialise the SDK
$sdk = new FeedpleSDK(
    apiKey:   'sk_live_...',
    db:       $pdo,
    identity: $identity,
);

// 4. Start the SDK — this call blocks until stop() is called.
//    Run this script as a CLI worker or background process.
$sdk->run();

$sdk = new FeedpleSDK(
    // Required
    apiKey:   'sk_live_...',      // Your Feedple API key
    db:       $pdo,               // PDO connection
    identity: $identity,          // Identity (see below)

    // Schema sync
    autoSync:     true,           // Sync schema on startup and periodically (default: true)
    syncInterval: 60,             // Seconds between sync cycles (default: 60)

    // Connection
    reconnectEnabled:   true,     // Reconnect on disconnect (default: true)
    maxRetries:         null,     // Max reconnect attempts; null = unlimited (default: null)
    probeBeforeConnect: false,    // HTTP probe before WS handshake for clearer errors (default: false)

    // Optional
    logger: $psrLogger,           // PSR-3 LoggerInterface; defaults to stderr output
    wsUrl:  'https://...',        // Override the default Feedple server URL
);

use Feedple\Sdk\Core\Identity;

// Grant access to all tables
$adminIdentity = new Identity(
    name:      'admin',
    allTables: true,
);

// Restrict to specific tables only
$restrictedIdentity = new Identity(
    name:          'analytics-service',
    allowedTables: ['users', 'orders', 'products', 'events'],
    allTables:     false,   // default
);

// Trigger a schema sync manually.
// Safe to call while the event loop is running (e.g. via a signal handler).
$sdk->syncSchema();

use Feedple\Sdk\Core\SchemaServices;

$safeSchema = SchemaServices::filterSensitiveColumns($rawSchema);

$ir = [
    'operation' => 'query',              // always "query"
    'table'     => 'orders',            // primary FROM table
    'fields'    => [                    // columns to SELECT
        ['column' => 'orders.id',      'expression' => null,             'alias' => null],
        ['column' => 'orders.amount',  'expression' => 'sum',            'alias' => 'total'],
        ['column' => 'orders.user_id', 'expression' => 'count(distinct)','alias' => 'unique_users'],
    ],
    'joins' => [                         // JOIN clauses
        [
            'table'     => 'users',
            'on_left'   => 'orders.user_id',
            'on_right'  => 'users.id',
            'join_type' => 'INNER',      // "INNER" or "LEFT"
        ],
    ],
    'filters' => [                       // WHERE conditions (ANDed together)
        ['column' => 'orders.status', 'operator' => 'eq',  'value' => 'active'],
        ['column' => 'orders.amount', 'operator' => 'gte', 'value' => 100],
    ],
    'group_by' => ['orders.status'],
    'having'   => [['column' => 'orders.id', 'operator' => 'gt', 'value' => 5]],
    'order_by' => ['orders.created_at DESC'],
    'limit'    => 100,
    'offset'   => 0,
];

$sdk->stop();

// Graceful shutdown on SIGTERM / SIGINT
pcntl_async_signals(true);
pcntl_signal(SIGTERM, fn() => $sdk->stop());
pcntl_signal(SIGINT,  fn() => $sdk->stop());

$sdk->run();

use Feedple\Sdk\Core\IrBuilder;

['sql' => $sql, 'params' => $params] = IrBuilder::buildQueryFromIr($ir);

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

use Feedple\Sdk\Core\SqlCompiler;
use Feedple\Sdk\Core\PolicyEngine;
use Feedple\Sdk\Core\Identity;

$identity = new Identity(name: 'reader', allowedTables: ['users', 'orders']);
$compiler = new SqlCompiler(new PolicyEngine($identity));

// Throws RuntimeException if SQL references a denied table
$safeSql = $compiler->compile('SELECT id, name FROM users WHERE active = 1');

use Feedple\Sdk\Core\SchemaServices;
use Feedple\Sdk\Core\Identity;

// Inspect schema
$schema = SchemaServices::getSchema($pdo, $identity);

// Hash for change detection
$hash = SchemaServices::generateSchemaHash($schema);

// Check if sync is needed
$changed = SchemaServices::shouldSyncSchema($oldSchema, $newSchema);

// Strip sensitive columns
$safe = SchemaServices::filterSensitiveColumns($schema);

use Feedple\Sdk\Core\PolicyEngine;
use Feedple\Sdk\Core\Identity;

$policy = new PolicyEngine(new Identity(name: 'reader', allowedTables: ['orders']));

$policy->canAccessTable('orders');   // true
$policy->canAccessTable('invoices'); // false

$policy->validateIrAccess($ir);      // throws RuntimeException if denied

use Feedple\Sdk\Core\JsonSerializer;

$json   = JsonSerializer::encode($data);   // handles DateTime, objects
$array  = JsonSerializer::decode($json);
$normal = JsonSerializer::normalize($value); // recursive normalization only

// worker.php

edpleSDK;
use Feedple\Sdk\Core\Identity;

$pdo = new PDO(getenv('DATABASE_URL'));

$sdk = new FeedpleSDK(
    apiKey:       getenv('FEEDPLE_API_KEY'),
    db:           $pdo,
    identity:     new Identity(name: 'prod', allTables: true),
    syncInterval: 300,
);

$sdk->run();

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$logger = new Logger('feedple');
$logger->pushHandler(new StreamHandler('php://stderr', Logger::INFO));

$sdk = new FeedpleSDK(
    apiKey:   'sk_live_...',
    db:       $pdo,
    identity: $identity,
    logger:   $logger,
);

use function Feedple\Sdk\FEEDPLE_WS_URL;

// Development (default)
$sdk = new FeedpleSDK(apiKey: '...', db: $pdo, identity: $identity);

// Production
$sdk = new FeedpleSDK(
    apiKey:  '...',
    db:      $pdo,
    identity: $identity,
    wsUrl:   'wss://feedple-ai-614817435356.us-central1.run.app/api/v1/tenants/ws',
);

namespace Feedple\Sdk;

class FeedpleSDK
{
    public function __construct(
        string            $apiKey,
        \PDO              $db,
        Identity          $identity,
        bool              $autoSync            = true,
        int               $syncInterval        = 60,
        bool              $reconnectEnabled    = true,
        ?int              $maxRetries          = null,
        bool              $probeBeforeConnect  = false,
        ?LoggerInterface  $logger              = null,
        ?string           $wsUrl               = null,
    );

    public function run(): void;          // starts event loop (blocking)
    public function syncSchema(): void;   // manually trigger schema sync
    public function stop(): void;         // stop event loop and close connection
    public function buildCompiler(): SqlCompiler; // raw SQL RBAC compiler
}

namespace Feedple\Sdk\Core;

class Identity
{
    public function __construct(
        public readonly ?string $name,
        public readonly array   $allowedTables = [],
        public readonly bool    $allTables     = false,
    );
}

namespace Feedple\Sdk\Core;

class PolicyEngine
{
    public function __construct(Identity $identity);

    public function canAccessTable(string $table): bool;
    public function validateIrAccess(array $ir): void; // throws RuntimeException if denied
}

namespace Feedple\Sdk\Core;

class IrBuilder
{
    /** @return array{sql: string, params: list<mixed>} */
    public static function buildQueryFromIr(array $ir): array;
}

namespace Feedple\Sdk\Core;

class SchemaServices
{
    public const SENSITIVE_COLUMNS: string[];

    public static function getSchema(\PDO $db, Identity $identity): array;
    public static function generateSchemaHash(array $schema): string;
    public static function normalizeSchema(array $schema): string;
    public static function shouldSyncSchema(array $old, array $new): bool;
    public static function filterSensitiveColumns(array $schema): array;
}

namespace Feedple\Sdk\Core;

class SqlCompiler
{
    public function __construct(PolicyEngine $policy, string $dialect = 'postgres');

    public function parse(string $sql): array;            // ['sql' => …, 'tables' => […]]
    public function extractTables(string $sql): array;    // string[]
    public function validateAccess(array $tables): void;  // throws RuntimeException if denied
    public function compile(string $sql): string;
}

namespace Feedple\Sdk\Core;

class JsonSerializer
{
    public static function encode(mixed $data): string;
    public static function decode(string $json): array;
    public static function normalize(mixed $value): mixed;
}
bash
php worker.php