PHP Luminova: Schema.org Structured Data & Metadata Embedding
Embed Schema.org JSON-LD, canonical links, and social metadata in application templates.
Schema combines site-wide defaults with page data. Embed that data as JSON-LD in a standard web page, with article or product details where applicable. Use the same page settings to render canonical links, descriptions, and social metadata in the document head.
Class Definition
- Full namespace:
Luminova\Components\Seo\Schema - This class implements Luminova\Interface\LazyObjectInterface.
- This class is final.
Default Configuration
The schema comes with a default configuration that applies globally across your website. These defaults ensure that important data is always present, even if no custom settings are added for a specific page. However, you can override these settings on a per-page basis whenever you need to customize the schema.
For detailed instructions, see the Default Schema Configuration.
Examples
You can load the Schema class either directly in your Controllers (for page-specific data) or globally in your Application (to set defaults used site-wide).
Initialize Global metadata
If you want to set up your Schema globally, initialize it inside your application's onCreate() method. This way, every page will automatically have a base configuration without needing to repeat the setup.
Example: using Application in onCreate
// /app/Application.php
namespace App;
use Luminova\Components\Seo\Schema;
use Luminova\Foundation\Core\AbstractApplication;
use Luminova\Routing\Router;
class Application extends AbstractApplication
{
public ?Schema $schema = null;
/**
* Runs once when the application boots.
* Ideal place to configure global SEO schema defaults.
*/
protected function onCreate(): void
{
// Initialize the page schema
$this->schema = new Schema();
// Current request URI path (e.g, company/about)
$uri = Router::getUriPath();
// Set the current page URL
$this->schema->setUrl(
APP_URL, // Base application URL (e.g. https://example.com)
$uri // Set current request URI
);
// Optionally set a canonical URL www alias (e.g. https://www.example.com)
$this->schema->setCanonical(rtrim(APP_URL_ALIAS, '/') . '/' . ltrim($uri, '/'));
}
}Controllers can set page-specific values before rendering a view. Schema settings are shared within the PHP process, so create the page metadata before rendering the view.
Add article metadata in a controller
This example assumes an application model named App\Models\Blog whose find() method returns an article with the fields shown. The controller looks up the article, adds structured data, then passes the record and schema to the view.
// /app/Controllers/Http/WebpageController.php
namespace App\Controllers\Http;
use App\Models\Blog;
use Luminova\Base\Http\AbstractController;
use Luminova\Attributes\Route;
class WebpageController extends AbstractController
{
#[Route('/', methods: ['GET'])]
public function index(): int
{
// Uses only the global schema defaults
return $this->view('index', ['schema' => $this->app->schema]);
}
#[Route('/blog/(:number)', methods: ['GET'])]
public function blog(string $id): int
{
$fullUrl = $this->request->getUrl();
$blog = (new Blog())->find((int) $id);
if (!$blog) {
return $this->view('not-found', status: 404);
}
// Add structured data specific to this blog article
$schema = $this->app->schema;
$schema->isArticle()->setTitle($blog->title)->setDescription($blog->intro);
$schema->setObject([
'url' => $fullUrl,
'article' => [
'type' => 'Article', /* Could also be 'TechArticle' */
'description' => $blog->intro,
'headline' => $blog->headline,
'title' => $blog->title,
'word_count' => strlen($blog->body), /* Ideally store this with the blog e.g, $blog->word_count */
'keywords' => [$blog->category, ...$blog->tags],
'section' => [$blog->category],
'published_date' => $blog->published_on,
'modified_date' => $blog->modified_on,
'author' => [
'id' => $blog->author_username,
'name' => htmlspecialchars($blog->author, ENT_QUOTES, 'UTF-8'),
'url' => "https://example.com/author/{$blog->author_username}",
'image' => [
'url' => "https://example.com/assets/authors/{$blog->author_username}.png",
]
],
],
'breadcrumbs' => [
[
'url' => rtrim(APP_URL, '/') . '/blog/',
'name' => 'All Our Blog',
],
],
/* Add more fields as needed... */
]);
return $this->view('blog', [
'schema' => $schema,
'id' => $id,
'blog' => $blog,
]);
}
}Render metadata in a view
Once your Schema object is initialized, you can embed SEO meta tags and structured data directly inside your view templates. This will output the appropriate <meta> tags and JSON-LD script blocks automatically.
Example:
With PHP template options exposed as view properties, the schema option is available as $this->_schema.
<!-- /resources/Views/index.php -->
<!DOCTYPE html>
<html>
<head>
<!-- Embed the page’s SEO meta tags -->
<?= $this->_schema->getHeadTags(); ?>
<!-- Set the page title -->
<title><?= htmlspecialchars($this->_schema->getTitle(), ENT_QUOTES, 'UTF-8') ?></title>
<!-- Embed JSON-LD structured data -->
<script type="application/ld+json"><?= json_encode(
$this->_schema->toJsonLd(),
JSON_HEX_TAG | JSON_THROW_ON_ERROR
) ?></script>
</head>
<body>
<p>Welcome to my webpage!</p>
</body>
</html>Embedding Data Inside the Blog Template
The blog content passed to your view is available using framework's template options.
Example template output:
<!-- /resources/Views/blog.php -->
<!DOCTYPE html>
<html>
<head>
<!-- Embed SEO meta tags for the blog page -->
<?= $this->_schema->getHeadTags();?>
<!-- Add page title dynamically -->
<title><?= htmlspecialchars($this->_schema->getTitle(), ENT_QUOTES, 'UTF-8') ?></title>
<!-- Embed structured JSON-LD schema -->
<script type="application/ld+json"><?= json_encode(
$this->_schema->toJsonLd(),
JSON_HEX_TAG | JSON_THROW_ON_ERROR
) ?></script>
</head>
<body>
<article>
<h1><?= htmlspecialchars($this->_blog->headline, ENT_QUOTES, 'UTF-8') ?></h1>
<p><?= htmlspecialchars($this->_blog->body, ENT_QUOTES, 'UTF-8') ?></p>
</article>
</body>
</html>With this setup, your blog page now outputs complete structured data for search engines.
How it works:
getHeadTags()adds meta tags like description, OpenGraph, and Twitter card data.getTitle()outputs the properly formatted page title.toJsonLd()supplies the data for the script. The template usesJSON_HEX_TAGto encode angle brackets in dynamic content. For fixed, trusted metadata,getJsonLdScript()returns the complete script tag.
For more examples, see SEO integrations.
Add product metadata
Set product data before embedding JSON-LD on a product page. Pass an offer to include the price, currency, and stock status in the graph.
use Luminova\Components\Seo\Schema;
$schema = (new Schema())
->setUrl('https://example.com', 'shop/desk-lamp')
->setTitle('Desk lamp')
->setDescription('An adjustable desk lamp with a warm light.')
->isProduct()
->setValue('product', [
'name' => 'Desk lamp',
'sku' => 'LAMP-01',
'offers' => [
'price' => 49.00,
'currency' => 'USD',
'availability' => 'InStock',
],
]);
echo $schema->getJsonLdScript();Methods
__construct
Creates a Schema instance with default configuration.
Loads schema defaults from your app config, sets the base URL for the current page, and prepares value filters used to remove empty entries from structured data.
public function __construct(private ?array $filterValues = null)Parameters:
| Parameter | Type | Description |
|---|---|---|
$filterValues | array<int,mixed>\|null | Values to remove from graph nodes. Uses the built-in filters when omitted (default: null). |
The built-in filters remove empty strings, zero, null, empty arrays, and arrays containing one empty string.
getInstance
Returns the shared singleton instance of this class.
Creates a new instance on first call and reuses the same instance for subsequent calls.
public static function getInstance(): selfReturn:
self - Return a shared singleton instance.
isArticle
Marks the current schema as an article.
public function isArticle(bool $article = true): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$article | bool | Whether this schema represents an article (default: true). |
Return:
self - Returns the current Schema instance.
isProduct
Marks the current schema as a product.
public function isProduct(bool $product = true): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$product | bool | Whether this schema represents a product (default: true). |
Return:
self - Returns the current Schema instance.
setUrl
Sets the URL for the current schema.
Use to link the schema object to a specific page or resource.
public function setUrl(string $url, string $uri = ''): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$url | string | Base URL (e.g. https://example.com). |
$uri | string | URI path to append to the base URL (default: ''). |
Return:
self - Returns the current Schema instance.
Use setCanonical() to add a canonical link tag.
setObject
Merges custom schema data into the current page object.
Use this when you want to populate or override schema properties for the current page using an associative array. By default, empty values in the array are ignored, but you can choose to retain them.
public function setObject(array $object, bool $keepEmpty = false): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$object | array<string,mixed> | Key-value pairs representing schema properties (e.g., ['article' => ['headline' => 'My Page']). |
$keepEmpty | bool | Whether to retain empty values (default: false). |
Return:
self - Return the instance of schema.
Use setValue() to update a single field.
setValue
Sets or overrides a single schema property for the current page.
Use this when you need to update a specific schema value without replacing the entire configuration array.
public function setValue(string $key, mixed $value): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The schema property name (e.g., headline, author). |
$value | mixed | The value to assign to this property. |
Return:
self - Return the instance of schema.
setTitle
Sets the current page title with automatic site branding.
Appends the application name when it is absent from the title.
public function setTitle(string $title): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$title | string | The base title of the page (without app name). |
Return:
self - Return the instance of schema.
Useful for consistent SEO page titles across your application.
setDescription
Sets the current page description for schema object.
Adds or updates the page description used in the page metadata.
public function setDescription(string $description): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$description | string | The meta description for the page. |
Return:
self - Return the instance of schema.
setHeadline
Sets article page headline for SEO and structured data.
The headline is often used by search engines and schema.org markup to summarize the content.
Headline should be short and clear.
public function setHeadline(string $headline): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$headline | string | The headline text for the page. |
Return:
self - Return the instance of schema.
setCanonical
Adds a canonical URL to avoid duplicate content issues.
Canonical URLs tell search engines which version of a page is authoritative. Each call appends a canonical link. For a typical page, call this method once.
public function setCanonical(string $url): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$url | string | The base canonical URL (e.g., https://example.com). |
Return:
self - Return the instance of schema.
Note:If multiple canonicals are added, ensure they are all valid and relevant to avoid conflicting signals to search engines.
getObject
Retrieve a schema configuration value by key with optional query string processing.
Looks up the resolved page value, including page-specific overrides.
- If the value is an array, it is returned as-is.
- If the value is a link or canonical, it may have query parameters appended.
public function getObject(string $key, mixed $default = null): mixedParameters:
| Parameter | Type | Description |
|---|---|---|
$key | string | The configuration key to retrieve. |
$default | mixed | Default value to return if the key is not found (default: null). |
Return:
mixed - Return the resolved configuration value, or $default if not found.
getTitle
Get the current page title set in the schema.
Uses the internal schema data to fetch the title text. Returns an empty string if not set.
public function getTitle(): stringReturn:
string - Return the current page title.
getUrl
Get the current page link (URL) set in the schema.
Uses the internal schema data to fetch the url value. Returns an empty string if not set.
public function getUrl(): stringReturn:
string - Return the current page link URL.
getJsonLdString
Get the JSON-LD representation of the schema.
Converts the current schema data to a JSON string, using unescaped slashesand pretty-print formatting for readability.
public function getJsonLdString(): stringReturn:
string - Return the schema as a JSON-LD string.
getJsonLdScript
Get the JSON-LD schema as an HTML <script> tag.
Use this helper with trusted metadata and a fixed script ID. For dynamic page content, use the encoding shown in Render metadata in a view.Should be called once per page to output the schema object inside an application/ld+json script tag.
public function getJsonLdScript(?string $id = null): stringParameters:
| Parameter | Type | Description |
|---|---|---|
$id | string\|null | Optional ID attribute for the script tag (default: null). |
Return:
string - Return the HTML <script> element containing the schema.
getHeadTags
Returns standard, Open Graph, and Twitter tags to embed in the document head.
Combines keywords, description, canonical URLs, social metadata and custom tagsinto properly formatted HTML <meta> or <link> tags. Should be called once perpage to embed SEO information.
public function getHeadTags(): stringReturn:
string - Returns the HTML meta and link tags.
toJsonLd
Get the complete structured data schema for the current page.
Builds and returns the schema.org data as an associative array.
Use the array when you need to inspect or encode the graph yourself.
public function toJsonLd(): arrayReturn:
array<string,mixed> - Returns the structured data graph for the current page.
| Key | Type | Description |
|---|---|---|
@context | string | Schema.org vocabulary URL, https://schema.org. |
@graph | array<int,array<string,mixed>> | List of schema nodes. Fields vary by node type and page data. |