rumenx/php-seo

AI-powered, framework-agnostic PHP package for automated SEO optimization. Intelligently generates meta tags, titles, descriptions, and alt texts using configurable AI providers or manual patterns.

Fund package maintenance!
RumenDamyanov

Installs: 968

Dependents: 0

Suggesters: 0

Security: 0

Stars: 3

Watchers: 0

Forks: 1

Open Issues: 1

pkg:composer/rumenx/php-seo


README

CI Analyze Style CodeQL Dependabot codecov

php-seo is a modern, AI-powered, framework-agnostic PHP package for automated SEO optimization. It intelligently generates meta tags, titles, descriptions, and alt texts using configurable AI providers or manual patterns, seamlessly integrating with Laravel, Symfony, or any PHP project.

โœจ Features

๐Ÿค– AI-Powered Automation

  • Intelligent Content Analysis: AI reads and analyzes page content to generate optimal titles, descriptions, and meta tags
  • Image Analysis: Automatically generates alt text and titles for images by analyzing context
  • Social Media Optimization: Generates platform-specific meta tags (Open Graph, Twitter Cards, etc.)
  • Multi-Provider Support: Integration with popular AI models (GPT-4o, Claude 3.5, Gemini 1.5, Grok, Ollama)

๐Ÿ”ง Manual Configuration Mode

  • Pattern-Based Generation: Generate titles and descriptions using configurable patterns
  • Manual Override: Full manual control over all SEO elements
  • Fallback Systems: Graceful degradation when AI services are unavailable
  • Template-Based: Use predefined templates for consistent SEO across pages

๐Ÿ—๏ธ Framework Integration

  • Laravel: Native service provider, facades, config publishing, middleware
  • Symfony: Bundle integration with services and configuration
  • Generic PHP: Framework-agnostic core that works with any PHP project

๐Ÿš€ Modern PHP

  • Type-safe: Full PHP 8.2+ type declarations and strict types
  • Fluent Interface: Chainable methods for elegant, readable code
  • Extensible: Plugin architecture for custom analyzers and generators
  • High Performance: Optimized for speed with caching and lazy loading
  • 100% Test Pass Rate: Comprehensive test suite with 453+ passing tests using Pest

๐Ÿ’Ž Advanced Features

  • PSR-16 Caching: Built-in caching support for improved performance (80%+ faster)
  • Rate Limiting: Automatic API throttling with token bucket algorithm
  • Structured Data: JSON-LD generation for Schema.org (Article, WebPage, Organization, Breadcrumb)
  • Cost Optimization: 80-90% reduction in AI API costs through intelligent caching
  • Production Ready: PHPStan level 6, 100% test coverage, strict types

๐Ÿ“– Quick Links

๐Ÿ“ฆ Installation

Install via Composer:

composer require rumenx/php-seo

Requirements

  • PHP 8.2 or higher
  • ext-json
  • ext-curl

๐Ÿš€ Usage Examples

Laravel Example

Basic Setup

// In your controller
use Rumenx\PhpSeo\SeoManager;

public function show(Post $post, SeoManager $seo)
{
    $content = view('posts.content', compact('post'))->render();

    $seoData = $seo->analyze($content, [
        'title' => $post->title,
        'url' => request()->url(),
        'image' => $post->featured_image,
        'author' => $post->author->name,
        'published_at' => $post->published_at->toISOString(),
    ])->generateAll();

    return view('posts.show', compact('post', 'seoData'));
}

Blade Template

@extends('layouts.app')

@section('head')
    {!! app('seo')->renderMetaTags($seoData) !!}
@endsection

@section('content')
    <!-- Your content here -->
@endsection

Using Facade

use Rumenx\PhpSeo\Facades\Seo;

// Quick generation
$title = Seo::analyze($content)->generateTitle();
$description = Seo::generateDescription();
$metaTags = Seo::generateMetaTags();

// Complete SEO data
$seoData = Seo::analyze($content, $metadata)->generateAll();

Middleware Integration

// In app/Http/Kernel.php
protected $routeMiddleware = [
    'seo' => \Rumenx\PhpSeo\Integrations\Laravel\SeoMiddleware::class,
];

// In your routes
Route::get('/posts/{post}', [PostController::class, 'show'])
    ->middleware('seo');

Symfony Example

Controller Usage

use Rumenx\PhpSeo\SeoManager;
use Symfony\Component\HttpFoundation\Response;

class PostController extends AbstractController
{
    public function show(Post $post, SeoManager $seo): Response
    {
        $content = $this->renderView('post/content.html.twig', ['post' => $post]);

        $seoData = $seo->analyze($content, [
            'title' => $post->getTitle(),
            'url' => $this->generateUrl('post_show', ['id' => $post->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
            'image' => $post->getFeaturedImage(),
            'author' => $post->getAuthor()->getName(),
        ])->generateAll();

        return $this->render('post/show.html.twig', [
            'post' => $post,
            'seo_data' => $seoData,
        ]);
    }
}

Twig Template

{% extends 'base.html.twig' %}

{% block head %}
    {{ seo_meta_tags(seo_data)|raw }}
{% endblock %}

{% block body %}
    <!-- Your content here -->
{% endblock %}

Generic PHP Example

require 'vendor/autoload.php';

use Rumenx\PhpSeo\SeoManager;
use Rumenx\PhpSeo\Config\SeoConfig;

// Basic usage
$seo = new SeoManager();
$content = file_get_contents('page-content.html');

$seoData = $seo->analyze($content, [
    'title' => 'My Page Title',
    'url' => 'https://example.com/page',
])->generateAll();

// Output meta tags
echo $seo->renderMetaTags($seoData);

// With custom configuration
$config = new SeoConfig([
    'title' => [
        'pattern' => '{title} - {site_name}',
        'site_name' => 'My Website',
        'max_length' => 55,
    ],
    'mode' => 'ai',
    'ai' => [
        'provider' => 'openai',
        'api_key' => $_ENV['OPENAI_API_KEY'],
    ],
]);

$seo = new SeoManager($config);
$optimizedTitle = $seo->analyze($content)->generateTitle();

Caching for Performance

Reduce AI costs by 80-90% and improve speed with PSR-16 caching:

use Rumenx\PhpSeo\SeoManager;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\Cache\Psr16Cache;

// Setup Redis cache (or any PSR-16 implementation)
$redisClient = RedisAdapter::createConnection('redis://localhost');
$cache = new Psr16Cache(new RedisAdapter($redisClient));

// Initialize with caching
$seo = new SeoManager($config, $cache);

// First call: analyzes and caches
$seo->analyze($content)->generateAll();

// Second call: instant retrieval from cache (80%+ faster!)
$seo->analyze($content)->generateAll();

See examples/caching.php for complete example.

Structured Data (JSON-LD)

Generate Schema.org structured data for rich snippets:

// Configure structured data
$config = new SeoConfig([
    'structured_data' => [
        'enabled' => true,
        'types' => [
            'article' => true,
            'breadcrumb' => true,
        ],
        'publisher' => [
            'name' => 'Your Site Name',
            'logo' => 'https://example.com/logo.png',
        ],
    ],
]);

$seo = new SeoManager($config);
$seo->analyze($content, [
    'title' => 'Article Title',
    'author' => 'John Doe',
    'published_date' => '2024-01-15T10:00:00Z',
]);

// Render in <head> section
echo $seo->renderStructuredData();

See examples/structured-data.php for complete example.

Complete Integration

For a full example showing all features, see examples/complete-integration.php.

โš™๏ธ Configuration

Laravel Configuration

Publish the configuration file:

php artisan vendor:publish --provider="Rumenx\PhpSeo\Integrations\Laravel\SeoServiceProvider"

Edit config/seo.php:

return [
    'mode' => 'hybrid', // 'ai', 'manual', 'hybrid'
    'ai' => [
        'provider' => 'openai',
        'api_key' => env('SEO_AI_API_KEY'),
        'model' => 'gpt-4o-mini', // Best cost/performance (Dec 2024)
    ],
    'title' => [
        'pattern' => '{title} | {site_name}',
        'site_name' => env('APP_NAME'),
        'max_length' => 60,
    ],
    // ... more configuration
];

Environment Variables

# Basic settings
SEO_ENABLED=true
SEO_MODE=hybrid
SEO_CACHE_ENABLED=true

# AI Provider
SEO_AI_PROVIDER=openai
SEO_AI_API_KEY=your-api-key-here
SEO_AI_MODEL=gpt-4o-mini

# Title settings
SEO_TITLE_PATTERN="{title} | {site_name}"
SEO_SITE_NAME="My Website"

# Social media
SEO_OG_SITE_NAME="My Website"
SEO_TWITTER_SITE="@mywebsite"

๐Ÿค– AI Providers

OpenAI (GPT-4/5)

$config = new SeoConfig([
    'ai' => [
        'provider' => 'openai',
        'api_key' => 'your-openai-api-key',
        'model' => 'gpt-4o-mini', // Best cost/performance (Dec 2024)
    ],
]);

Anthropic (Claude)

$config = new SeoConfig([
    'ai' => [
        'provider' => 'anthropic',
        'api_key' => 'your-anthropic-api-key',
        'model' => 'claude-3-5-sonnet-20241022', // Latest Claude 3.5 Sonnet (Oct 2024)
    ],
]);

Google (Gemini)

$config = new SeoConfig([
    'ai' => [
        'provider' => 'google',
        'api_key' => 'your-google-api-key',
        'model' => 'gemini-1.5-flash', // Latest Gemini 1.5 Flash (Dec 2024)
    ],
]);

Local AI (Ollama)

$config = new SeoConfig([
    'ai' => [
        'provider' => 'ollama',
        'api_url' => 'http://localhost:11434',
        'model' => 'llama2',
    ],
]);

Multiple Providers (Fallback)

$config = new SeoConfig([
    'ai' => [
        'provider' => 'openai',
        'api_key' => 'primary-key',
        'fallback_providers' => [
            ['provider' => 'anthropic', 'api_key' => 'backup-key'],
            ['provider' => 'ollama', 'api_url' => 'http://localhost:11434'],
        ],
    ],
]);

๐ŸŽฏ Advanced Features

Fluent Interface

The package supports method chaining for elegant, readable code:

// Chain analyze() with generation methods
$title = $seo->analyze($content, $metadata)->generateTitle();
$description = $seo->analyze($content)->generateDescription();

// Chain all SEO generation
$seoData = $seo
    ->analyze($content, ['title' => 'My Page'])
    ->generateAll();

// Chain configuration methods
$seo = (new SeoManager())
    ->setPageData($customData)
    ->setCache($cacheImplementation);

// Schema classes support fluent interface
$article = (new ArticleSchema())
    ->setHeadline('My Article Title')
    ->setDescription('Article description')
    ->setAuthor('John Doe')
    ->setDatePublished('2024-01-15T10:00:00Z')
    ->setImage('https://example.com/image.jpg');

// All setter methods return $this for chaining
$breadcrumb = (new BreadcrumbListSchema())
    ->addItem('Home', '/', 1)
    ->addItem('Blog', '/blog', 2)
    ->addItem('Article', '/blog/article', 3);

Available Chainable Methods:

  • analyze(string $content, array $metadata = []): self
  • setPageData(array $data): self
  • setCache(CacheInterface $cache): self
  • withConfig(SeoConfig $config): self
  • All Schema setter methods return static for chaining

Custom Analyzers

use Rumenx\PhpSeo\Contracts\AnalyzerInterface;

class CustomContentAnalyzer implements AnalyzerInterface
{
    public function analyze(string $content, array $metadata = []): array
    {
        // Your custom analysis logic
        return [
            'custom_data' => $this->extractCustomData($content),
            // ... other data
        ];
    }

    public function supports(string $contentType): bool
    {
        return $contentType === 'custom/format';
    }
}

// Use your custom analyzer
$seo = new SeoManager(
    config: $config,
    contentAnalyzer: new CustomContentAnalyzer()
);

Custom Generators

use Rumenx\PhpSeo\Contracts\GeneratorInterface;

class CustomTitleGenerator implements GeneratorInterface
{
    public function generate(array $pageData): string
    {
        // Your custom generation logic
        return $this->createCustomTitle($pageData);
    }

    public function generateCustom(mixed $customInput, array $pageData = []): string
    {
        // Handle custom input
        return $this->processCustomTitle($customInput, $pageData);
    }

    public function supports(string $type): bool
    {
        return $type === 'title';
    }
}

Batch Processing

$posts = Post::all();
$seoResults = [];

foreach ($posts as $post) {
    $content = $post->getContent();
    $metadata = [
        'title' => $post->getTitle(),
        'url' => $post->getUrl(),
        'author' => $post->getAuthor(),
    ];

    $seoResults[$post->getId()] = $seo
        ->analyze($content, $metadata)
        ->generateAll();
}

๐Ÿงช Testing & Development

Running Tests

# Run all tests (453 tests, 1247 assertions - 100% passing! โœ…)
composer test

# Run tests with coverage
composer test-coverage

# Generate HTML coverage report
composer test-coverage-html

# Run specific test
./vendor/bin/pest tests/Unit/SeoManagerTest.php

# Run specific test group
./vendor/bin/pest --filter="OllamaProvider"

# Run with verbose output
./vendor/bin/pest --verbose

Test Coverage

The package maintains 100% test pass rate with comprehensive test coverage:

  • โœ… 453 passing tests across all components
  • โœ… 1247 assertions ensuring code quality
  • โœ… Unit tests for all core functionality
  • โœ… Integration tests for Laravel and Symfony
  • โœ… AI Provider tests for OpenAI, Anthropic, Google, xAI, and Ollama
  • โœ… Generator tests for titles, descriptions, and meta tags
  • โœ… Analyzer tests for content processing
  • โœ… Validator tests for response validation

Code Quality

# Check coding standards
composer style

# Fix coding standards
composer style-fix

# Run static analysis
composer analyze

# Run all quality checks
composer quality

๐Ÿ“š Documentation

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

๐Ÿ”’ Security

If you discover a security vulnerability, please review our Security Policy for responsible disclosure guidelines.

๐Ÿ’ Support

If you find this package helpful, consider:

๐Ÿ“„ License

MIT License. Please see the license file for more information.

๐Ÿ† About

php-seo is created and maintained by Rumen Damyanov. It aims to bring the same level of quality and ease-of-use to SEO optimization.

SEO Package Family

This package is part of a multi-language SEO ecosystem:

  • @rumenx/seo - JavaScript/TypeScript SEO package for Node.js and browsers

    • ๐Ÿ“ฆ NPM Package
    • ๐Ÿ’ป GitHub Repository
    • โšก Framework-agnostic with React, Vue, Angular integrations
    • ๐Ÿš€ Works in both Node.js and browser environments
  • php-seo (this package) - PHP SEO package for Laravel, Symfony, and any PHP project

    • ๐Ÿ˜ PHP 8.2+ with full type safety
    • ๐Ÿค– AI-powered content generation
    • ๐Ÿ—๏ธ Framework-agnostic with Laravel/Symfony integrations
  • go-seo (planned) - Go SEO package

    • ๐Ÿš€ High-performance SEO optimization for Go applications
    • Coming soon!

All packages share similar APIs and best practices, making it easy to work across different tech stacks.

Related Projects

  • php-chatbot - AI powered chatbot package
  • php-sitemap - Framework-agnostic sitemap generation
  • php-feed - Framework-agnostic rss feed generation
  • php-geolocation - Framework-agnostic geolocation detection and handling for PHP
  • More projects coming soon!

Framework-agnostic AI-powered SEO optimization for modern PHP applications.