PHP code example of refinder / laravel-sdk

1. Go to this page and download the library: Download refinder/laravel-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/ */

    

refinder / laravel-sdk example snippets


use Refinder\LaravelSdk\Facades\Refinder;

// Execute SEO analysis
$result = Refinder::seo()->execute([
    'content' => 'Your article content here...',
    'content_type' => 'article',
    'language' => 'en',
]);

// Access the results
echo $result->output->metaTitle;           // "Optimized SEO Title..."
echo $result->output->metaDescription;     // "Meta description..."
echo $result->output->seoScore->overall;   // 75 (0-100)

// Check if score is passing (>= 60)
if ($result->output->seoScore->isPassing()) {
    echo "SEO score is good!";
}

return [
    // Your API key (R_API_KEY'),

    // API base URL
    'base_url' => env('REFINDER_BASE_URL', 'https://api.refinder.ai/api/v1'),

    // Request timeout in seconds (tool executions can take 10-30s)
    'timeout' => env('REFINDER_TIMEOUT', 120),

    // Retry on 5xx/timeout errors (never retries 4xx)
    'retries' => env('REFINDER_RETRIES', 2),
    'retry_delay_ms' => env('REFINDER_RETRY_DELAY', 1000),

    // Response caching for identical inputs
    'cache' => [
        'enabled' => env('REFINDER_CACHE_ENABLED', false),
        'ttl' => env('REFINDER_CACHE_TTL', 60),   // minutes
        'prefix' => 'refinder_',
    ],

    // Dispatch Laravel events after tool executions
    'events' => env('REFINDER_EVENTS', true),

    // Log channel (null = default channel)
    'log_channel' => env('REFINDER_LOG_CHANNEL', null),
];

use Refinder\LaravelSdk\DTOs\SeoInput;
use Refinder\LaravelSdk\Facades\Refinder;

$input = new SeoInput(
    content: $article->body,
    url: route('articles.show', $article),
    contentType: 'article',
    language: 'en',
    depth: 'advanced',
    targetKeywords: ['AI tools', 'machine learning'],
    brandName: 'MyBrand',
    industry: 'Technology',
);

$result = Refinder::seo()->execute($input);

// Basic analysis
$result = Refinder::seo()->basic($content, 'en');

// Advanced analysis (default)
$result = Refinder::seo()->advanced($content, 'en');

// Full technical analysis
$result = Refinder::seo()->technical($content, 'en');

$result = Refinder::seo()->execute(['content' => $text]);
$seo = $result->output;

// Meta tags
echo $seo->metaTitle;           // string (50-60 chars)
echo $seo->metaDescription;     // string (150-160 chars)

// Keywords
$seo->keywords->primary;        // ['keyword1', 'keyword2', ...]
$seo->keywords->secondary;      // ['keyword3', 'keyword4', ...]
$seo->keywords->longTail;       // ['long tail phrase', ...]
$seo->keywords->all();          // All keywords merged

// Content Analysis
$seo->contentAnalysis->readabilityScore;    // 'excellent', 'good', 'needs_improvement'
$seo->contentAnalysis->wordCountAssessment; // string
$seo->contentAnalysis->contentQuality;      // 'high', 'medium', 'low'
$seo->contentAnalysis->keyTopicsCovered;    // ['topic1', ...]

// SEO Score (0-100)
$seo->seoScore->overall;    // 75
$seo->seoScore->content;    // 70
$seo->seoScore->keywords;   // 80
$seo->seoScore->structure;  // 75
$seo->seoScore->isPassing(); // true (>= 60)

// Optimization Suggestions
foreach ($seo->optimizationSuggestions as $suggestion) {
    echo $suggestion->category;    // 'content', 'technical', 'structure', 'keywords'
    echo $suggestion->priority;    // 'high', 'medium', 'low'
    echo $suggestion->suggestion;  // "Add structured data markup"
    echo $suggestion->details;     // "Implementing JSON-LD..."
    $suggestion->isHighPriority(); // bool
}

// Heading Structure
echo $seo->headingStructure->suggestedH1;  // string
$seo->headingStructure->suggestedH2s;      // array of strings
$seo->headingStructure->suggestedH3s;      // array of strings

// Execution metadata
echo $result->id;                        // UUID
echo $result->status;                    // 'completed'
echo $result->usage->totalTokens;        // 1276
echo $result->usage->executionTimeSeconds(); // 14.5
echo $result->model->name;              // 'Qwen Plus'
echo $result->model->provider;          // 'alibaba'

$platform = Refinder::me();

echo $platform->id;           // 1
echo $platform->name;         // "My Platform"
echo $platform->slug;         // "my-platform"
echo $platform->website;      // "https://example.com"
echo $platform->description;  // "Platform description"
echo $platform->isActive;     // true
echo $platform->createdAt;    // "2026-02-08T09:00:00+00:00"

$sub = Refinder::subscription();

echo $sub->plan->name;                // "Pro"
echo $sub->plan->slug;                // "pro"
echo $sub->plan->maxRequestsPerMonth; // 1000
echo $sub->plan->maxRequestsPerDay;   // 100
echo $sub->plan->features;            // ['advanced_seo', 'api_access', ...]
echo $sub->status;                     // "active"
$sub->isActive();                      // true
$sub->isOnTrial();                     // false

// Current month usage
$usage = Refinder::usage();

// Custom date range
$usage = Refinder::usage('2026-01-01', '2026-01-31');

echo $usage->totalRequests; // 47
echo $usage->totalTokens;   // 62340
echo $usage->totalCost;     // 0.12468
echo $usage->periodFrom;    // "2026-02-01"
echo $usage->periodTo;      // "2026-02-08"

// Daily breakdown
foreach ($usage->daily as $day) {
    echo $day->date;           // "2026-02-08"
    echo $day->tool;           // "seo"
    echo $day->requestsCount;  // 12
    echo $day->tokensUsed;     // 15600
    echo $day->estimatedCost;  // 0.0312
}

// List executions (paginated)
$executions = Refinder::executions(perPage: 10, page: 1);

echo $executions->total;        // 47
echo $executions->currentPage;  // 1
echo $executions->lastPage;     // 5
echo $executions->hasMorePages(); // true

foreach ($executions->items as $exec) {
    echo $exec->id;                    // UUID
    echo $exec->tool;                  // "seo"
    echo $exec->status;                // "completed"
    echo $exec->usage->totalTokens;    // 1276
    echo $exec->createdAt;             // ISO 8601 string
}

// Get specific execution
$exec = Refinder::execution('d47181d4-d26b-4224-a7f7-4c973b66f8fa');
if ($exec->isCompleted()) {
    echo $exec->output->metaTitle;
}

$tools = Refinder::tools();
// Returns array of tool definitions

use Refinder\LaravelSdk\Exceptions\AuthenticationException;
use Refinder\LaravelSdk\Exceptions\RateLimitException;
use Refinder\LaravelSdk\Exceptions\SubscriptionException;
use Refinder\LaravelSdk\Exceptions\ToolException;
use Refinder\LaravelSdk\Exceptions\ValidationException;
use Refinder\LaravelSdk\Facades\Refinder;

try {
    $result = Refinder::seo()->execute(['content' => $text]);

    return response()->json([
        'seo' => $result->output,
        'tokens' => $result->usage->totalTokens,
    ]);

} catch (ValidationException $e) {
    // Input validation failed (422)
    return response()->json(['error' => $e->errors], 422);

} catch (RateLimitException $e) {
    // Quota exceeded (429)
    return response()->json([
        'error' => 'Rate limit reached',
        'limit' => $e->limit,
        'current' => $e->current,
    ], 429);

} catch (SubscriptionException $e) {
    // Subscription issue (403)
    return response()->json(['error' => $e->getMessage()], 403);

} catch (AuthenticationException $e) {
    // Invalid API key (401)
    Log::critical('Refinder API key is invalid!', ['code' => $e->errorCode]);
    return response()->json(['error' => 'Service unavailable'], 503);

} catch (ToolException $e) {
    // AI processing failed (500/502)
    Log::error('Tool failed', ['execution_id' => $e->executionId]);
    return response()->json(['error' => 'Please retry'], 502);
}

use Refinder\LaravelSdk\Events\ToolExecuted;

Event::listen(ToolExecuted::class, function (ToolExecuted $event) {
    Log::info("Refinder tool executed", [
        'tool' => $event->tool,           // "seo"
        'execution_id' => $event->executionId,
        'tokens' => $event->tokensUsed,
        'time_ms' => $event->executionTimeMs,
    ]);
});

use Refinder\LaravelSdk\Events\ToolExecutionFailed;

Event::listen(ToolExecutionFailed::class, function (ToolExecutionFailed $event) {
    Log::error("Refinder tool failed", [
        'tool' => $event->tool,
        'error_code' => $event->errorCode,
        'message' => $event->errorMessage,
        'execution_id' => $event->executionId,
    ]);
});

use Refinder\LaravelSdk\Events\RateLimitApproaching;

Event::listen(RateLimitApproaching::class, function (RateLimitApproaching $event) {
    Log::warning("Approaching rate limit", [
        'type' => $event->limitType,       // "daily" or "monthly"
        'limit' => $event->limit,
        'current' => $event->current,
        'percentage' => $event->percentageUsed,
    ]);
});

$usage = Refinder::usage();
$sub = Refinder::subscription();

$used = $usage->totalRequests;
$limit = $sub->plan->maxRequestsPerMonth;
$remaining = $limit - $used;
$percentage = ($used / $limit) * 100;

echo "Used {$used}/{$limit} ({$percentage}%) this month.";
echo "{$remaining} requests remaining.";

use Refinder\LaravelSdk\Facades\Refinder;

public function test_seo_analysis()
{
    Refinder::fake();

    // Your code calls the SDK as normal
    $result = Refinder::seo()->execute(['content' => 'Test content for SEO']);

    // Results come from the fake
    $this->assertEquals('completed', $result->status);
    $this->assertNotNull($result->output->metaTitle);
    $this->assertTrue($result->output->seoScore->isPassing());

    // Assert the tool was called
    Refinder::assertToolExecuted('seo');
    Refinder::assertToolExecutedCount('seo', 1);
}

Refinder::fake();

Refinder::fakeToolExecution('seo', [
    'meta_title' => 'Custom Test Title',
    'meta_description' => 'Custom test description.',
    'keywords' => [
        'primary' => ['custom keyword'],
        'secondary' => ['test'],
        'long_tail' => ['custom long tail'],
    ],
    'content_analysis' => [
        'readability_score' => 'excellent',
        'word_count_assessment' => 'Perfect length.',
        'content_quality' => 'high',
        'key_topics_covered' => ['testing'],
    ],
    'optimization_suggestions' => [],
    'heading_structure' => [
        'suggested_h1' => 'Custom H1',
        'suggested_h2s' => ['Custom H2'],
        'suggested_h3s' => [],
    ],
    'seo_score' => [
        'overall' => 95,
        'content' => 90,
        'keywords' => 95,
        'structure' => 95,
    ],
]);

$result = Refinder::seo()->execute(['content' => 'Any content']);
$this->assertEquals('Custom Test Title', $result->output->metaTitle);
$this->assertEquals(95, $result->output->seoScore->overall);

Refinder::fake();

// Assert tool was executed
Refinder::assertToolExecuted('seo');

// Assert exact count
Refinder::assertToolExecutedCount('seo', 3);

// Assert nothing was executed
Refinder::assertNothingExecuted();

$product = Product::find(1);

$result = Refinder::seo()->execute([
    'content' => $product->description,
    'url' => route('products.show', $product),
    'content_type' => 'product',
    'brand_name' => $product->brand->name,
    'industry' => $product->category->name,
    'target_keywords' => $product->tags->pluck('name')->toArray(),
]);

if ($result->isCompleted()) {
    $product->seoMeta()->updateOrCreate([], [
        'title' => $result->output->metaTitle,
        'description' => $result->output->metaDescription,
        'keywords' => $result->output->keywords->all(),
        'h1' => $result->output->headingStructure->suggestedH1,
        'score' => $result->output->seoScore->overall,
        'analyzed_at' => now(),
    ]);
}

use Refinder\LaravelSdk\Facades\Refinder;
use Refinder\LaravelSdk\Exceptions\RateLimitException;

class AnalyzeArticleSeo implements ShouldQueue
{
    public int $tries = 3;
    public int $backoff = 60;

    public function __construct(public Article $article) {}

    public function handle(): void
    {
        try {
            $result = Refinder::seo()->execute([
                'content' => $this->article->body,
                'content_type' => 'article',
                'language' => $this->article->locale,
                'depth' => 'advanced',
            ]);

            $this->article->update([
                'seo_title' => $result->output->metaTitle,
                'seo_description' => $result->output->metaDescription,
                'seo_score' => $result->output->seoScore->overall,
                'seo_analyzed_at' => now(),
            ]);
        } catch (RateLimitException $e) {
            $this->release(300); // retry in 5 minutes
        }
    }
}

// Dispatch for all unanalyzed articles
Article::whereNull('seo_analyzed_at')->chunk(50, function ($articles) {
    foreach ($articles as $article) {
        AnalyzeArticleSeo::dispatch($article);
    }
});

// Get platform info
$platform = Refinder::me();
echo "Platform: {$platform->name} | Active: " . ($platform->isActive ? 'Yes' : 'No');

// Get subscription
$sub = Refinder::subscription();
echo "Plan: {$sub->plan->name} | Monthly: {$sub->plan->maxRequestsPerMonth}";

// Get usage
$usage = Refinder::usage();
echo "Requests: {$usage->totalRequests} | Tokens: {$usage->totalTokens}";
echo "Cost: \${$usage->totalCost}";

// Browse execution history
$executions = Refinder::executions(perPage: 10);
foreach ($executions->items as $exec) {
    echo "{$exec->id} | {$exec->tool} | {$exec->status} | {$exec->usage->totalTokens} tokens";
}
bash
php artisan vendor:publish --tag=refinder-config