承接 christian98/opengraph-laravel 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

christian98/opengraph-laravel

最新稳定版本:v3.0.0

Composer 安装命令:

composer require christian98/opengraph-laravel

包简介

This package provides a neat way to generate Open-Graph tags.

README 文档

README

pipeline status coverage report Latest Release Packagist Downloads Packagist License Packagist Version Packagist PHP Version Support Maintenance Treeware (Trees)

A small, expressive package to build Open Graph (og:) meta tags and optional Twitter cards in Laravel applications.

Installation

Install with Composer:

composer require christian98/opengraph-laravel

The package auto-registers a service provider and a facade alias (Opengraph) via Composer extras for Laravel.

Configuration

The package includes a publishable config file. To publish it into your application run:

php artisan vendor:publish --provider="OpengraphLaravel\\OpengraphLaravel\\OpengraphLaravelServiceProvider"

Currently the configuration file is empty, but publishing it allows future customization.

Usage

The package supports two workflows, but the most common and recommended approach in Laravel apps is to mutate the container-scoped instance via the provided Facade. This matches the Blade component (<x-opengraph::tags />) — the Facade resolves the OpenGraphData from the container and forwards method calls to it.

  • Primary (recommended) — mutate the container-scoped instance via the Opengraph Facade:
use Opengraph; // facade

// update the container-bound OpenGraphData instance for the current request
Opengraph::title('My page title')
    ->description('A short description of the page')
    ->typeWebsite()
    ->siteName('My Site')
    ->image('https://example.com/image.jpg', function ($img) {
        $img->width('1200')->height('630')->alt('An example image');
    })
    ->url('https://example.com/page');

// in your Blade layout (inside <head>) render the tags
// <x-opengraph::tags />

This approach mutates the request-scoped OpenGraphData instance that the Blade component will read. This is a common pattern: call Opengraph::title(...) (and other methods) directly, then render the component via <x-opengraph::tags />.

  • Builder / explicit binding (rare)

Sometimes you may want to work with a standalone builder instance or prepare an instance and bind it explicitly into the container. This is supported but less common:

// standalone builder and render immediately
$html = Opengraph::builder()
    ->title('Standalone')
    ->typeWebsite()
    ->image('https://example.com/img.jpg')
    ->url('https://example.com')
    ->toHtml();

// or prepare a builder and replace the container-bound instance for the request
Opengraph::use(
    Opengraph::builder()
        ->title('Explicit')
        ->typeArticle(fn($a) => $a->publishedTime(new \DateTime('2025-01-01')))
        ->image('https://example.com/img.jpg')
        ->url('https://example.com/article')
);

(Use this explicit builder() / use() pattern only when you need a standalone instance or want to replace the container binding explicitly.)

API overview

Most methods on the builder return the builder instance for fluent usage. The important pieces are:

  • Opengraph::builder(): OpenGraphData — returns a fresh builder instance.
  • Opengraph::use(OpenGraphData $data): void — replace the container-bound instance with the given data for the current request.
  • OpenGraphData methods (chainable):

    • title(string)
    • description(string)
    • determiner(string)
    • locale(string)
    • localeAlternate(string)
    • siteName(string)
    • url(string)
    • image(string $url, ?callable $options = null)
    • video(string $url, ?callable $options = null)
    • audio(string $url, ?callable $options = null)
    • clearImages(), clearVideos(), clearAudios()
    • typeArticle(callable $alter), typeBook(callable $alter), typeProfile(callable $alter), typeWebsite()
    • twitterSummary(callable $alter), twitterPlayer(callable $alter), twitterApp(callable $alter)
  • Rendering:

    • toMetaTags(): MetaTagList — returns a list object you can manipulate programmatically.
    • toHtml(): string — returns the HTML string with tags.

Notes and validations:

  • The builder marks itself as "showing" when you call most setter methods. If no values are set the component will render nothing.
  • When rendering (toMetaTags / toHtml) the package enforces some requirements and will throw an exception if they are not met:
    • title is required
    • an object type (e.g. website, article, profile) must be specified
    • at least one image is required
    • url is required

Blade components

The package registers a Blade component namespace opengraph which exposes a Tags component. Use it as:

<x-opengraph::tags />

This will output the Open Graph and (if configured) Twitter meta tags for the current request's OpenGraphData instance.

Extending / Custom tags

The builders and helpers expose toMetaTags() which returns a MetaTagList. You can add additional tags programmatically:

$list = Opengraph::builder()
    ->title('...')
    ->typeWebsite()
    ->image('...')
    ->url('...')
    ->toMetaTags();

$list->add('og:custom', 'value');
$html = $list->collect()->map(fn($t) => $t->toHtml())->join("\n");

Examples

Here are a few concrete examples showing common usage patterns — these use the Facade/container-mutation approach by default.

  • Article with multiple tags and timestamps
use Opengraph;

Opengraph::title('Deep dive into Open Graph')
    ->description('How to structure Open Graph metadata for your posts')
    ->typeArticle(function ($article) {
        $article->publishedTime(new \DateTime('2025-06-01'))
            ->modifiedTime(new \DateTime('2025-06-02'))
            ->author('https://example.com/authors/jane-doe')
            ->section('Technology')
            ->tags(['opengraph', 'laravel', 'seo']);
    })
    ->image('https://example.com/img/article-cover.jpg', fn($img) => $img->width('1200')->height('630')->alt('Article cover'))
    ->url('https://example.com/posts/opengraph');

// then render in Blade: <x-opengraph::tags />
  • Profile example
Opengraph::title('Jane Doe')
    ->typeProfile(function ($p) {
        $p->firstName('Jane')->lastName('Doe')->username('jane')->gender(\OpengraphLaravel\OpengraphLaravel\ObjectType\ProfileGender::Female);
    })
    ->image('https://example.com/avatar.jpg')
    ->url('https://example.com/authors/jane');

// then render in Blade: <x-opengraph::tags />
  • Twitter cards (Summary and Player)
// Summary card
Opengraph::title('Example with Twitter summary')
    ->typeWebsite()
    ->image('https://example.com/img/summary.jpg')
    ->url('https://example.com/summary')
    ->twitterSummary(function ($t) {
        $t->creator('@example')
            ->title('Twitter Title')
            ->description('Short description for Twitter')
            ->image('https://example.com/img/summary.jpg');
    });

// Player card
Opengraph::title('Example with Twitter player')
    ->typeWebsite()
    ->image('https://example.com/img/player.jpg')
    ->url('https://example.com/player')
    ->twitterPlayer(function ($t) {
        $t->title('Player title')
            ->description('A video or audio player')
            ->image('https://example.com/img/player.jpg')
            ->playerUrl('https://example.com/embed/player')
            ->playerWidth('640')
            ->playerHeight('360');
    });

// render in Blade: <x-opengraph::tags />

Supported types

The package currently includes support for these Open Graph object types and Twitter card types.

  • Object types
TypeHow to setNotes
website->typeWebsite()Basic website type.
article->typeArticle(fn($a) => ...)Supports published/modified/expiration times, author, section and tags.
book->typeBook(fn($b) => ...)Basic book type (no extra properties implemented).
profile->typeProfile(fn($p) => ...)Supports first_name, last_name, username and gender.
  • Twitter card types
TypeHow to setNotes
summary->twitterSummary(fn($t) => ...)Summary or summary_large_image (toggle with ->largeImage()).
player->twitterPlayer(fn($t) => ...)Player card with player URL and dimensions.
app->twitterApp(fn($t) => ...)App card with references for iPhone, iPad and Google Play.

Unsupported / Not implemented types

Some Open Graph and media helper types are present as method stubs in the API but are intentionally not implemented yet and will throw a LogicException if called. These are safe to know about so you don't attempt to use them in production yet.

  • Object / music types with stubs on OpenGraphData:

    • typeMusicAlbum() — not implemented
    • typeMusicPlaylist() — not implemented
    • typeMusicRadioStation() — not implemented
  • Video types with stubs on OpenGraphData:

    • typeVideoMovie() — not implemented
    • typeVideoEpisode() — not implemented
    • typeVideoTvShow() — not implemented
    • typeVideoOther() — not implemented
  • Notes:

    • typeBook() exists but currently only sets og:type: book and does not provide additional book-specific properties.
    • If you need one of the not-implemented types, consider adding custom tags via toMetaTags() and MetaTagList::add() until the helpers are implemented.

Testing

The package includes PHPUnit tests. Run them with:

vendor/bin/phpunit -c ./phpunit.xml

Contributing

Contributions are welcome. Please open issues or merge requests on the repository: https://gitlab.com/christian98/opengraph-laravel

License

This package is Treeware. If you use it in production, consider contributing by planting a tree: https://plant.treeware.earth/christian98/opengraph-laravel

Original author: Christian Holländer

统计信息

  • 总下载量: 1.97k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-10-04