brick/schema
brick/schema is a PHP library to define, validate, and serialize data structures using schemas. Model arrays and objects with clear rules, enforce types and constraints, and convert to/from common formats for safer data exchange and persistence.
## Getting Started
### Minimal Setup
1. **Installation**
```bash
composer require brick/schema:^0.2.0
Note: Requires PHP 8.1+ (breaking change in 0.2.0). Add to composer.json if using a monorepo or custom package setup.
First Use Case: Generating Basic Schema Markup
use Brick\Schema\ItemList;
use Brick\Schema\Thing;
$itemList = new ItemList();
$itemList->setName('Summer Sale Items');
$item = new Thing();
$item->setName('Wireless Headphones');
$item->setDescription('Noise-cancelling wireless headphones');
$itemList->addItem($item);
echo $itemList->toHtml();
Outputs a valid ItemList schema in HTML microdata format.
Where to Look First
Thing, ItemList, BreadcrumbList, Organization, and LocalBusiness for common use cases.Schema::html() and Schema::jsonLd() for serialization.SchemaTypeList now supports proper iterator template arguments (useful for type-safe iteration in IDEs).public function getProductSchema(Product $product)
{
$productSchema = new Product();
$productSchema->setName($product->name);
$productSchema->setDescription($product->description);
$productSchema->setImage($product->imageUrl);
$productSchema->setOfferedThrough(new Organization([
'name' => 'Your Store',
'url' => url('/'),
]));
return $productSchema;
}
Integration Tip: Use Laravel's service container to bind Brick\Schema\Thing implementations to interfaces for dependency injection.
Note: All non-inherited classes are now final (0.2.0 breaking change), so avoid extending them directly.
public function getBreadcrumbSchema(array $crumbs)
{
$breadcrumbList = new BreadcrumbList();
$breadcrumbList->setItemList([
new ListItem([
'name' => 'Home',
'item' => url('/'),
]),
new ListItem([
'name' => 'Category',
'item' => url('/category'),
]),
new ListItem([
'name' => 'Product',
'item' => url('/product'),
]),
]);
return $breadcrumbList;
}
Integration Tip: Hook into Laravel's Breadcrumbs package (if used) to auto-generate schema dynamically.
public function renderJsonLdSchema()
{
$schema = new Organization([
'name' => 'Your Company',
'url' => url('/'),
'logo' => asset('logo.png'),
'sameAs' => ['https://twitter.com/yourhandle'],
]);
return response()->json($schema->toJsonLd(), 200, [
'Content-Type' => 'application/ld+json',
]);
}
Integration Tip: Use middleware to inject JSON-LD schemas into responses for APIs or SPAs.
Note: Compatible with brick/structured-data v0.2 (0.2.0 feature).
Create a SchemaService to encapsulate logic:
class SchemaService
{
public function createArticleSchema(Article $article)
{
return new Article([
'headline' => $article->title,
'description' => $article->excerpt,
'datePublished' => $article->published_at->toIso8601String(),
'author' => new Person([
'name' => $article->author->name,
]),
'publisher' => new Organization([
'name' => config('app.name'),
'logo' => asset('logo.png'),
]),
]);
}
}
Integration Tip: Register the service in Laravel's container:
$this->app->bind(SchemaService::class, function ($app) {
return new SchemaService();
});
Create a custom Blade directive for easy schema injection:
// app/Providers/BladeServiceProvider.php
Blade::directive('schema', function ($expression) {
return "<?php echo app('schema')->render({$expression}); ?>";
});
Usage:
@schema('article', $post)
public function handle($request, Closure $next)
{
$response = $next($request);
if ($request->routeIs('products.*')) {
$schema = app('schema')->getProductSchema($request->product);
$response->headers->set('X-Schema', $schema->toJsonLd());
}
return $response;
}
Extend Laravel's JsonResponse to include schemas:
class SchemaJsonResponse extends JsonResponse
{
public function __construct($data, $status = 200, array $headers = [], $options = 0, $schema = null)
{
parent::__construct($data, $status, $headers, $options);
if ($schema) {
$this->setSchema($schema);
}
}
protected function setSchema($schema)
{
$this->headers->set('X-Schema', $schema->toJsonLd());
}
}
PHP 8.1 Requirement (Breaking Change)
Your PHP version (8.0) does not satisfy requirement brick/schema:^0.2.0 (>=8.1).brick/schema:^0.1.0.Final Classes (Breaking Change)
Thing, ItemList, etc., as they are now final.$customSchema = new Thing();
$customSchema->setAdditionalProperty('customField', 'value');
Property Validation
price for a Person) will generate malformed markup.Nested Objects
Offer inside AggregateRating) can be error-prone.$product->setOffers([
new Offer([
'priceCurrency' => 'USD',
'price' => 19.99,
'availability' => 'https://schema.org/InStock',
]),
]);
Date Handling
YYYY-MM-DD). Laravel's Carbon instances work, but raw strings may fail.toIso8601String():
$event->setStartDate($event->date->toIso8601String());
URL Normalization
url() or asset() helpers:
$item->setImage(url('images/product.jpg'));
Validation Errors
dd($schema->toJsonLd());
Missing Properties
setAdditionalProperty() for custom or experimental properties:
$item->setAdditionalProperty('customProperty', 'value');
Namespace Collisions
setName vs. Laravel's name attribute).$item->setAdditionalData(['custom' => ['field' => 'value']]);
final, use composition:
How can I help you explore Laravel packages today?