Skip to content

Instantly share code, notes, and snippets.

@bergie
Created March 4, 2011 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bergie/854630 to your computer and use it in GitHub Desktop.
Save bergie/854630 to your computer and use it in GitHub Desktop.
Event-driven programming example with PHP5 and Midgard2
<?php
// Open Midgard connection
$config = new midgard_config();
$config->read_file_at_path(ini_get('midgard.configuration_file'));
// Do stuff when we get a DB connection
midgard_connection::get_instance()->connect('connected', function($connection) {
echo "Connected, Midgard version " . mgd_version() . "\n";
});
midgard_connection::get_instance()->open_config($config);
// Whenever an article is updated we want to know about it
midgard_object_class::connect_default('org_midgardproject_news_article', 'action-updated', function($object) {
echo $object->title . " was updated\n";
});
// Query for articles
$q = new midgard_query_select(
new midgard_query_storage('org_midgardproject_news_article')
);
$q->add_order(new midgard_query_property('metadata.created'), SORT_DESC);
// When query starts executing we may add constraints to it
$q->connect('execution-start', function($executor) {
// Only query articles with a title that starts with "Hello"
$executor->set_constraint
(
new midgard_query_constraint
(
new midgard_query_property('title'),
'LIKE',
new midgard_query_value('Hello%')
)
);
});
// When query is done, we may do something with the results
$q->connect('execution-end', function($executor) {
// Increase the score of each queried article by one
array_walk($executor->list_objects(), function($object) {
$object->metadata->score++;
$object->update();
});
});
$q->execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment