spatie/schema-org

repository·main·Indexed 23 days ago

https://github.com/spatie/schema-org

A fluent PHP builder for Schema.org types and an ld+json generator. It provides a type-safe way to create structured data based on the official Schema.org vocabulary, supporting JSON-LD export, Graph abstractions for linked entities, and Multi-Typed Entities (MTEs).

Tokens
8.1K
Snippets
11
Records
37
Agent score
79%

What's inside spatie/schema-org

  1. Manage multiple nodes of the same type in a Graph

    main

    When a Graph contains multiple entities of the same type (e.g., multiple Person nodes), you can use unique identifiers to track and modify them. If no identifier is provided, a reserved keyword default is used. You can add nodes via chaining or by passing a closure to the graph method.

    use Spatie\SchemaOrg\Graph;
    use Spatie\SchemaOrg\Person;
    
    $graph = new Graph();
    
    // add a Person using chaining with an identifier
    $graph->person('freekmurze')
        ->givenName('Freek')
        ->familyName('Van der Herten')
        ->alternateName('freekmurze');
    
    // add a Person using a closure
    $graph->person('sebastiandedeyne', function(Person $sebastian, Graph $graph): void {
        $sebastian
            ->givenName('Sebastian')
            ->familyName('De Deyne')
            ->alternateName('sebastiandedeyne');
    }); 
    
    // Update an existing node using its identifier
    $graph->person('gummibeer')
        ->givenName('Tom')
        ->familyName('Witkowski');
    
    // Hide a specific node by identifier
    $graph->hide(Person::class, 'random');
    
    echo json_encode($graph);
  2. How Multi-Typed Entities (MTEs) work

    main

    Multi-Typed Entities allow a single JSON-LD object to represent multiple Schema.org types simultaneously (e.g., an entity that is both a HotelRoom and a Product). The MultiTypedEntity class manages this by merging properties from different types using array_merge().

    Warning: Avoid defining the same property on different types within the same MTE, as the last one defined will overwrite previous values due to the underlying array_merge() behavior.

    use Spatie\SchemaOrg\MultiTypedEntity;
    use Spatie\SchemaOrg\Schema;
    
    $mte = new MultiTypedEntity();
    $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)
        );
    });
    
    echo json_encode($mte);
  3. How the Graph abstraction works

    main

    A Graph is a collection of multiple Schema.org entities that can be linked together. It is useful for generating a single @graph JSON-LD block. You can use overloaded methods on the Graph instance to create or retrieve existing entities within the graph. You can also use hide() to prevent specific types from being rendered in the final script tag.

    use Spatie\SchemaOrg\Graph;
    use Spatie\SchemaOrg\Organization;
    
    $graph = new Graph();
    
    $graph
        ->product()
        ->name('My cool Product')
        ->brand($graph->organization());
    
    // Hide the organization from the created script tag
    $graph->hide(Organization::class);
    
    // Somewhere else fill out the organization
    $graph
        ->organization()
        ->name('My awesome Company');
    
    echo $graph;
  4. Basic usage of Schema.org types

    main

    You can instantiate Schema.org types using the Spatie\SchemaOrg\Schema factory class or by using the new keyword. The library provides a fluent interface for setting properties. Most properties accept either a single value or an array of values.

    use Spatie\
    SchemaOrg\Schema;
    
    $localBusiness = Schema::localBusiness()
        ->name('Spatie')
        ->email('info@spatie.be')
        ->contactPoint(Schema::contactPoint()->areaServed('Worldwide'));
    
    echo $localBusiness->toScript();
  5. Conditionally modify schema with the `if` method

    main

    To avoid breaking a fluent method chain when setting properties conditionally, use the if() method. It accepts a boolean and a closure that receives the schema instance.

    use Spatie\SchemaOrg\LocalBusiness;
    use Spatie\SchemaOrg\Schema;
    
    $business = ['name' => 'Spatie'];
    
    $localBusiness = Schema::localBusiness()
        ->name($business['name'])
        ->if(isset($business['email']), function (LocalBusiness $schema) use ($business) {
            $schema->email($business['email']);
        });
  6. Advanced property manipulation

    main

    If the fluent API is insufficient, you can use these methods for manual property management:

    • setProperty(string $name, mixed $value): Sets a custom property.
    • getProperty(string $name, mixed $default = null): Retrieves a property value.
    • getProperties(): Returns all properties as an array.
    • addProperties(array $properties): Sets multiple properties at once.
    • getContext(): Returns the @context (usually https://schema.org).
    • getType(): Returns the @type of the entity.
    $localBusiness->setProperty('foo', 'bar');
    $localBusiness->getProperty('name'); // 'Spatie'
    $localBusiness->getProperty('bar', 'baz'); // 'baz'
    $localBusiness->getProperties(); // ['name' => 'Spatie', ...]
    $localBusiness->addProperties(['name' => 'value', 'foo' => 'bar']);
    $localBusiness->getContext(); // 'https://schema.org'
    $localBusiness->getType(); // 'LocalBusiness'
  7. Convert Schema objects to JSON-LD or arrays

    main

    Once you have built your schema object, you can export it in several formats:

    • toScript(): Returns a <script type="application/ld+json"> string.
    • toArray(): Returns the schema as a PHP array.
    • json_encode($object): Converts the object to a plain JSON string.
    • echo $object: Casting the object to a string produces the same output as toScript().
    $localBusiness->toArray();
    
    echo $localBusiness->toScript();
    
    echo $localBusiness; // Same output as `toScript()`
    
    echo json_encode($localBusiness);
  8. Use BookFormatType for book publication formats

    main
    The BookFormatType class represents the publication format of a book. It can be used to specify whether a book is an Audiobook, Ebook, Hardcover, etc. You can use the provided constants to ensure valid Schema.org enumeration values.
  9. Use the BusTrip class

    main
    The BusTrip class represents a trip on a commercial bus line. It implements several contracts including BusTripContract, IntangibleContract, ThingContract, and TripContract. You can use it to define structured data for bus journeys, including details like bus name, number, departure/arrival stops, and times.
  10. Configure BoardingPolicyType properties

    main

    The BoardingPolicyType class supports several properties to describe the boarding policy. Most methods accept a single value or an array of values/objects and return static to allow for method chaining.

    MethodAccepted Types
    additionalType($additionalType)string or string[]
    alternateName($alternateName)string or string[]
    description($description)TextObjectContract, TextObjectContract[], string, or string[]
    disambiguatingDescription($disambiguatingDescription)string or string[]
    identifier($identifier)PropertyValueContract, PropertyValueContract[], string, or string[]
    image($image)ImageObjectContract, ImageObjectContract[], string, or string[]
    mainEntityOfPage($mainEntityOfPage)CreativeWorkContract, CreativeWorkContract[], string, or string[]
    name($name)string or string[]
    potentialAction($potentialAction)ActionContract or ActionContract[]
    sameAs($sameAs)string or string[]
    subjectOf($subjectOf)CreativeWorkContract, CreativeWorkContract[], EventContract, or EventContract[]
    url($url)string or string[]
    supersededBy($supersededBy)Class, Class[], Enumeration, Enumeration[], Property, or Property[] (Static method)