# See this class in action

1. <?php
2. /**
3. * Model controller
4. *
5. * @author Mark Nielsen
6. * @package block_helloworld
7. */
9. defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
11. class block_helloworld_controller_model extends mr_controller_block {
12. /**
13. * Default screen
14. *
15. * Demo of mr_model_record_abstract
16. * Demo of mr_repository_abstract
17. */
18. public function view_action() {
19. global $CFG;
21. require_once($CFG->dirroot.'/blocks/helloworld/repository/helloworld.php');
23. $output = '';
25. #### DEMO CODE ####
26. // Our repository
27. $repo = new block_helloworld_repository_helloworld();
29. // Create a new instance of our model, set some properties
30. $bat = new block_helloworld_model_helloworld();
31. $bat->set_name('Fred')->set_foo('foo')->set_bar('bar');
33. // Save it, repository figures out its an insert based on id property
34. $repo->save($bat);
36. $output .= $this->helper->dump($bat, '$bat after insert (id is now set for us)', true);
38. // ...later we can get $bat
39. $model = $repo->get(array('id' => $bat->get_id()));
41. $output .= $this->helper->dump($model, 'Result of $repo->get(...)', true);
43. // Because of the @method in our repository class's PHPDoc,
44. // our ID can auto-complete on our $model, try it out!
45. $name = $model->get_name();
47. $output .= $this->helper->dump($name, 'Result of $model->get_name()', true);
49. // Now we can delete Fred!
50. $repo->delete($model);
52. $output .= $this->helper->dump($model, '$model after delete (id is now set to null)', true);
54. // Let's try iterating over a mr_repository_recordset!
56. // Make some records...
57. $repo->save(new block_helloworld_model_helloworld(array('name' => 'Tom')))
58. ->save(new block_helloworld_model_helloworld(array('name' => 'Martin')))
59. ->save(new block_helloworld_model_helloworld(array('name' => 'Kris')));
62. // Our repository mapper can return a special record set, mr_repository_recordset, that returns
63. // instances of our models when we iterate over it
64. $rs = $repo->get_recordset();
65. foreach ($rs as $instance) {
66. // This PHPDoc tells our IDE that $instance is an instance of block_helloworld_model_helloworld
67. /** @var $instance block_helloworld_model_helloworld */
68. $instance->get_name(); // Try it out!
70. $output .= $this->helper->dump($instance, '$instance dump in foreach loop', true);
72. $repo->delete($instance);
73. }
74. $rs->close(); // Don't forget to close, just like usual!
75. #### DEMO CODE ####
77. return $this->output->heading('Demo of mr_model_record_abstract and mr_repository_abstract').
78. $this->helper->highlight(__CLASS__, __FUNCTION__, true).
79. $this->output->box($output, 'generalbox boxaligncenter boxwidthnormal');
80. }
81. }

Documentation generated on Thu, 28 Jun 2012 16:33:51 -0700 by phpDocumentor 1.4.3