Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Easyrdf Laravel Package

sweetrdf/easyrdf

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require sweetrdf/easyrdf
    

    Ensure PHP 8.0+ and extensions (dom, mbstring, xmlreader) are enabled.

  2. First Use Case: Load and query an RDF file (e.g., FOAF profile):

    use EasyRdf\Graph;
    
    $graph = new Graph('https://example.com/foaf.rdf');
    $graph->load(); // Loads RDF from URL or file
    $primaryTopic = $graph->primaryTopic();
    echo $primaryTopic->get('foaf:name'); // Output: "John Doe"
    
  3. Key Classes to Explore:

    • EasyRdf\Graph: Core class for RDF graphs.
    • EasyRdf\Resource: Represents RDF resources.
    • EasyRdf\Sparql\Client: Execute SPARQL queries.
    • EasyRdf\Format: Handle RDF serialization/deserialization.

Implementation Patterns

1. Loading and Parsing RDF

  • From URLs/Files:

    $graph = new Graph('http://example.com/data.rdf');
    $graph->load(); // Auto-detects format (RDF/XML, Turtle, etc.)
    
  • From Strings:

    $graph = new Graph();
    $graph->parse($rdfString, 'application/rdf+xml');
    
  • Supported Formats:

    • Built-in: RDF/XML, Turtle, N-Triples, RDF/JSON.
    • Optional: ARC2, rapper (via CLI).

2. Querying Data

  • Basic Property Access:
    $name = $resource->get('foaf:name'); // Returns literal value
    $type = $resource->getType(); // Returns URI of the resource type
    
  • SPARQL Queries:
    $sparql = new \EasyRdf\Sparql\Client('http://dbpedia.org/sparql');
    $results = $sparql->query('SELECT ?name WHERE { ?person foaf:name ?name }');
    foreach ($results as $result) {
        echo $result->name;
    }
    

3. Graph Manipulation

  • Adding Data:
    $graph->addLiteral('http://example.org/subject', 'http://xmlns.com/foaf/0.1/name', 'Alice');
    $graph->addResource('http://example.org/subject', 'http://xmlns.com/foaf/0.1/knows', 'http://example.org/other');
    
  • Serializing:
    $serialized = $graph->serialise('application/n-triples');
    file_put_contents('output.nt', $serialized);
    

4. Type Mapping (Custom Classes)

  • Define a mapper for foaf:Person:
    $graph->setTypeMapper('foaf:Person', 'App\\Models\\FoafPerson');
    $person = $graph->getResource('http://example.org/person');
    // $person is now an instance of App\Models\FoafPerson
    

5. Graph Store Integration

  • Store/retrieve graphs via SPARQL 1.1 Graph Store:
    $store = new \EasyRdf\GraphStore('http://fuseki.example.org/');
    $store->save($graph, 'http://example.org/graph1');
    $retrievedGraph = $store->load('http://example.org/graph1');
    

6. Visualization (GraphViz)

  • Generate a GraphViz-compatible graph:
    $graphviz = $graph->getGraphviz();
    file_put_contents('graph.dot', $graphviz);
    

7. Open Graph Protocol

  • Extract OGP metadata from HTML:
    $html = file_get_contents('https://example.com');
    $graph = new \EasyRdf\Graph();
    $graph->parse($html, 'text/html', ['extractOpenGraph' => true]);
    echo $graph->get('og:title');
    

Gotchas and Tips

Common Pitfalls

  1. SPARQL CONSTRUCT/DESCRIBE Queries:

    • Some endpoints return SparqlResult instead of Graph. Use EasyRdf\Sparql\Client with updated headers (see #72).
    • Example fix:
      $client = new \EasyRdf\Sparql\Client('http://endpoint');
      $client->setAcceptHeader('application/rdf+xml'); // Force desired format
      $graph = $client->query('CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }');
      
  2. Turtle Parser Edge Cases:

    • Empty PREFIX declarations may cause errors (fixed in 1.18.1).
    • Boolean literals in Turtle (e.g., true, false) require explicit typing:
      $graph->addLiteral('http://example.org/subject', 'http://example.org/pred', 'true', 'http://www.w3.org/2001/XMLSchema#boolean');
      
  3. RDF/XML Parsing:

    • Elements with both xml:lang and datatype may break parsing (fixed in 1.18.2).
    • Use libxml for complex XML:
      libxml_use_internal_errors(true);
      $graph->parse($xmlString, 'application/rdf+xml');
      
  4. HTTP Client Dependencies:

    • zendframework/http was removed in 1.18.0. Use Laminas\Http\Client or Guzzle for custom HTTP logic.
  5. Label Generation:

    • Default label properties (e.g., rdfs:label, foaf:name) may not cover all cases. Use custom lists:
      $label = $resource->label(null, ['foaf:name', 'schema:title']);
      
  6. PHP 8+ Deprecations:

    • Avoid foreach on non-traversable objects (e.g., SparqlResult). Use:
      foreach ($result as $binding) { ... } // Correct
      foreach ($result->bindings as $binding) { ... } // Also works
      

Debugging Tips

  • Dump Graph Contents:
    echo $graph->dump(); // Human-readable output
    
  • Validate URIs:
    $uri = new \EasyRdf\Uri('http://example.org');
    if (!$uri->isValid()) { /* Handle error */ }
    
  • Check HTTP Responses: Enable debug mode for EasyRdf\Http\Client:
    $client = new \EasyRdf\Http\Client();
    $client->setDebug(true);
    

Performance Considerations

  • Caching: Cache parsed graphs or SPARQL results:
    $cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter();
    $graph = $cache->get('graph_key', function() use ($url) {
        $graph = new Graph($url);
        $graph->load();
        return $graph;
    });
    
  • Batch Loading: For large graphs, use streaming parsers (e.g., N-Triples) or chunked SPARQL queries.

Extension Points

  1. Custom Parsers/Serializers: Extend EasyRdf\Parser or EasyRdf\Serializer for new formats. Example:

    class CustomParser extends \EasyRdf\Parser {
        public function parse($data, $format) { ... }
    }
    $graph->registerParser('application/custom', new CustomParser());
    
  2. Type Mappers: Implement EasyRdf\TypeMapper\MapperInterface for custom object mapping:

    class CustomMapper implements \EasyRdf\TypeMapper\MapperInterface {
        public function map($resource, $type) { ... }
    }
    $graph->setTypeMapper('http://example.org/Type', new CustomMapper());
    
  3. HTTP Client Overrides: Replace the default client (e.g., for authentication):

    $graph->setHttpClient(new \GuzzleHttp\Client());
    

Configuration Quirks

  • Default Namespaces: Set default namespaces for cleaner URIs:
    $graph->setNamespace('foaf', 'http://xmlns.com/foaf/0.
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor