Created
March 4, 2011 13:44
-
-
Save bergie/854630 to your computer and use it in GitHub Desktop.
Event-driven programming example with PHP5 and Midgard2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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