SchemaBuilder
A simple library to generate Schema.org., (*1)
Quality
, (*2)
Installation
This library requires PHP 5.4 or later., (*3)
It is recommended that you install this library using Composer., (*4)
Dependencies
SchemaBuilder relies upon and requires the following dependencies:, (*5)
-
danielstjules/stringy - A PHP string manipulation library.
Getting Started
Build Schema.org Object
Start by instantiating your primary Schema.org object with the type of the object., (*6)
For example, to create a Book:, (*7)
<?php
$book = new NYPL\SchemaBuilder\Schema('Book');
Then, set the properties of the object wih the property name and value:, (*8)
<?php
$book->addProperty('name', 'Le concerto');
$book->addProperty('author', 'Ferchault, Guy');
The property can also contain other Schema.org objects:, (*9)
<?php
// First, build the Offer object
$offer = new Schema('Offer');
$offer->addProperty('availability', 'http://schema.org/InStock');
$offer->addProperty('serialNumber', 'CONC91000937');
// Then, set the "offers" property on the Book object with the Offer object
$book->addProperty('offers', $offer);
Output Schema.org as JSON-LD
When you have finished building your Schema.org object, output it in JSON-LD:, (*10)
<head>
...
<?php $book->outputJsonLd();
Output Schema.org as Microdata
When you have finished building your Schema.org object, you can output it in two ways:, (*11)
1. Properties Only
To output without a HTML wrapper use the outputMicrodata method with or without a property name., (*12)
// Output an Object
<div <?php $book->outputMicrodata(); ?> itemid="#record">
// Output an Object's property
<h1 <?php $book->outputMicrodata('name'); ?>><?php $book->outputProperty('name'); ?></h1>
If you do not specify a property name, microdata to describe the primary object will be generated., (*13)
Outputs:, (*14)
<div itemscope itemtype="http://schema.org/Book" itemid="#record">
<h1 itemprop="name">Le concerto</h1>
2. Wrapped Properties
To output with a property with a HTML wrapper specify the name of the property and the wrapper that you want to use:, (*15)
<?php $book->outputMicrodata('additionalType', 'link'); ?>
<?php $book->outputMicrodata('name', 'h3'); ?>
Outputs:, (*16)
<link itemprop="additionalType" href="http://schema.org/Product">
<h3 itemprop="name">Le concerto</h3>
Tests
From the project directory, tests can be ran using phpunit., (*17)