Models
SPARQLer provides an alternative object-oriented interface to query and handle resources, inspired by Laravel's Eloquent ORM.
The first step is to define your own Model class, and specify which rdf:type
it maps.
use MadBob\Sparqler\Model;
class EmailMessage extends Model
{
protected $class = 'schema:EmailMessage';
}
Then you have to init a Client, set it as "global" to permit implicit access, and "boot" all of your model classes (to properly init the TypeMapper).
use MadBob\Sparqler\Client;
$client = new Client($config);
$client->setAsGlobal();
$client->bootModels([
\EmailMessage::class,
]);
Now you can directly query RDF resources having the desired rdf:type
and obtain an array of your own Model instances, eventually enriched with your own methods and functions.
$messages = EmailMessage::query()->where('schema:dateSent', '>', Carbon::today()->subDays(2))->get();
$now = Carbon::now();
foreach($messages as $message) {
// Here, $message is an instance of EmailMessage::class
echo $message->get('schema:dateSent') . "\n";
$message->set('schema:dateRead', $now);
$message->save();
}
The Builder inited by Model's query()
function behaves mostly as the one used for CONSTRUCT queries, with some extra utilities.
The with()
method permits to eager load related resources, and make them directly available from the resulting graph.
use MadBob\Sparqler\Terms\Optional;
use Carbon\Carbon;
$messages = EmailMessage::query()
->where('schema:dateSent', '>', Carbon::today()->subDays(2))
->with(['schema:sender', new Optional('schema:messageAttachment')])->get();
Show generated query
The returned value is always an array of instances of your Model class, even when Resources of different types are involved. Those will be still accessible due relations, using the function inherited from the base Resource class.