- Notifications
You must be signed in to change notification settings - Fork138
A fluent builder Schema.org types and ld+json generator
License
spatie/schema-org
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
spatie/schema-org
provides a fluent builder forall Schema.org types and their properties. The code insrc
is generated from Schema.org'sJSON-LD standards file, so it provides objects and methods for the entire core vocabulary. The classes and methods are also fully documented as a quick reference.
useSpatie\SchemaOrg\Schema;$localBusiness = Schema::localBusiness() ->name('Spatie') ->email('info@spatie.be') ->contactPoint(Schema::contactPoint()->areaServed('Worldwide'));echo$localBusiness->toScript();
<scripttype="application/ld+json">{"@context":"https:\/\/schema.org","@type":"LocalBusiness","name":"Spatie","email":"info@spatie.be","contactPoint":{"@type":"ContactPoint","areaServed":"Worldwide"}}</script>
We invest a lot of resources into creatingbest in class open source packages. You can support us bybuying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address onour contact page. We publish all received postcards onour virtual postcard wall.
You can install the package via composer:
composer require spatie/schema-org
All types can be instantiated through theSpatie\SchemaOrg\Schema
factory class, or with thenew
keyword.
$localBusiness = Schema::localBusiness()->name('Spatie');// Is equivalent to:$localBusiness =newLocalBusiness();$localBusiness->name('Spatie');
All types also accept arrays of the expected data type, for example
sameAs
accepts a string or an array of strings.
All types also implement the SPL'sArrayAccess
for accessing the properties via array notation:
$anotherLocalBusiness =newLocalBusiness();var_dump(isset($anotherLocalBusiness['name']));// => false$anotherLocalBusiness['name'] ='Spatie';var_dump(isset($anotherLocalBusiness['name']));// => truevar_dump($anotherLocalBusiness['name']);// => 'Spatie'unset($anotherLocalBusiness['name']);var_dump(isset($anotherLocalBusiness['name']));// => false
Types can be converted to an array or rendered to a script.
$localBusiness->toArray();echo$localBusiness->toScript();echo$localBusiness;// Same output as `toScript()`
Additionally, all types can be converted to a plain JSON string by just callingjson_encode()
with your object:
echojson_encode($localBusiness);
I recommend double checking your structured data withGoogle's structured data testing tool.
As of v1.6.0, allEnumeration child types are available as classes with constants.
Schema::book()->bookFormat(Spatie\SchemaOrg\BookFormatType::Hardcover);
There's no full API documentation for types and properties. You can refer tothe source or tothe schema.org website.
If you don't want to break the chain of a large schema object, you can use theif
method to conditionally modify the schema.
useSpatie\SchemaOrg\LocalBusiness;useSpatie\SchemaOrg\Schema;$business = ['name' =>'Spatie'];$localBusiness = Schema::localBusiness() ->name($business['name']) ->if(isset($business['email']),function (LocalBusiness$schema)use ($business) {$schema->email($business['email']); });
As of v2.6.0 theidentifier
key is replaced by@id
for simple string identifiers. This is due to the definition for theld+json
syntax.
All schema.org syntaxes already have built-in representation for URIs and URLs, e.g. in Microdata 'itemid', in RDFa 1.1, 'resource',in JSON-LD, '@id'.
—schema.org/docs //PR#102 //PR#157
If you'd need to set a custom property, you can use thesetProperty
method.
$localBusiness->setProperty('foo','bar');
If you'd need to retrieve a property, you can use thegetProperty
method. You can optionally pass in a second parameter to provide a default value.
$localBusiness->getProperty('name');// 'Spatie'$localBusiness->getProperty('bar');// null$localBusiness->getProperty('bar','baz');// 'baz'
All properties can be retrieved as an array with thegetProperties
method.
$localBusiness->getProperties();// ['name' => 'Spatie', ...]
Multiple properties can be set at once using theaddProperties
method.
$localBusiness->addProperties(['name' =>'value','foo' =>'bar']);
Context and type can be retrieved with thegetContext
andgetType
methods.
$localBusiness->getContext();// 'https://schema.org'$localBusiness->getType();// 'LocalBusiness'
The Graph has a lot of methods and utilities - the type-safe and simplest way is to use the overloaded methods of theSpatie\SchemaOrg\Schema
class itself. These methods will get an already created or new instance of the requested schema.
$graph =newGraph();// Create a product and prelink organization$graph ->product() ->name('My cool Product') ->brand($graph->organization());// Hide the organization from the created script tag$graph->hide(\Spatie\SchemaOrg\Organization::class);// Somewhere else fill out the organization$graph ->organization() ->name('My awesome Company');// Render graph to script tagecho$graph;
With these tools the graph is a collection of all available schemas, can link these schemas with each other and prevent helper schemas from being rendered in the script-tag.
Sometimes you have to keep track of multiple Graph nodes of the same type - for example multiplePerson
nodes for different people in your Organization.To do so you are able to use node identifiers on your graph instance.If you don't provide an identifier a reserved keyworddefault
identifier will be used.
useSpatie\SchemaOrg\Graph;useSpatie\SchemaOrg\Person;$graph =newGraph();// add a Person using chaining$graph->person('freekmurze') ->givenName('Freek') ->familyName('Van der Herten') ->alternateName('freekmurze');// add a Person using closure$graph->person('sebastiandedeyne',function(Person$sebastian,Graph$graph):void {$sebastian ->givenName('Sebastian') ->familyName('De Deyne') ->alternateName('sebastiandedeyne');});// add a person using closure and second call with same identifier$graph->person('gummibeer',fn(Person$gummibeer) =>$gummibeer->alternateName('gummibeer'));$graph->person('gummibeer') ->givenName('Tom') ->familyName('Witkowski');$graph->person('random')->name('Random Person');// hide the random person from Graph$graph->hide(Person::class,'random');echojson_encode($graph);
{"@context":"https:\/\/schema.org","@graph":[ {"@type":"Person","givenName":"Freek","familyName":"Van der Herten","alternateName":"freekmurze" }, {"@type":"Person","givenName":"Sebastian","familyName":"De Deyne","alternateName":"sebastiandedeyne" }, {"@type":"Person","alternateName":"gummibeer","givenName":"Tom","familyName":"Witkowski" } ]}
Schema.org allowsmulti typed entities - to use them with this package you can use theMultiTypedEntity
class - which works similar to the graph.
$mte =newMultiTypedEntity();$mte->hotelRoom()->name('The Presidential Suite');$mte->product()->offers( Schema::offer() ->name('One Night') ->price(100000.00) ->priceCurrency('USD'));$mte->product(function (Product$product) {$product->aggregateRating( Schema::aggregateRating() ->bestRating(5) ->worstRating(4) );});echojson_encode($mte);
{"@context":"https:\/\/schema.org","@type":["HotelRoom","Product" ],"name":"The Presidential Suite","offers":{"@type":"Offer","name":"One Night","price":100000,"priceCurrency":"USD" },"aggregateRating":{"@type":"AggregateRating","bestRating":5,"worstRating":4 }}
There isn't a real rule in place how the properties are merged. It only usesarray_merge()
behind the scenes. So you should avoid defining the same property on different types in the MTE or be sure that all properties hold the same value that it's not important which property is used at the end.
- The
Float
type isn't available since it's a reserved keyword in PHP - The
Physician
type isn't available since it extends a type from thehealth
extension spec
Please seeCHANGELOG for more information what has changed recently.
$ composertest
Please seeCONTRIBUTING for details.
If you've found a bug regarding security please mailsecurity@spatie.be instead of using the issue tracker.
You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.
Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.
We publish all received postcardson our company website.
The MIT License (MIT). Please seeLicense File for more information.
About
A fluent builder Schema.org types and ld+json generator