Skip to content

Instantly share code, notes, and snippets.

@intel352
Created March 14, 2012 01:06
Show Gist options
  • Save intel352/2033132 to your computer and use it in GitHub Desktop.
Save intel352/2033132 to your computer and use it in GitHub Desktop.
Example usage of ActiveDocument
<?php
class TestController extends Controller {
public function actionIndex() {
$person = TestPerson::model()->findByAttributes(array('name' => 'Parent'));
if ($person) {
CVarDumper::dump(array('person FROM ACTIVEDOCUMENT' => $person->object->data), 10, true);
CVarDumper::dump(array('person stepchildren LASTNAME ASC (relation criteria)' => array_map(function($c) {
/**
* @var TestPersonComposite $c
*/
return $c->object->data;
}, $person->stepChildren)), 10, true);
CVarDumper::dump(array('person stepchildren LIMIT 2 (getRelated criteria+existing relation criteria)' => array_map(function($c) {
/**
* @var TestPersonComposite $c
*/
return $c->object->data;
}, $person->getRelated('stepChildren', true, array(), array(), array('limit' => 2)))), 10, true);
Yii::app()->end();
} else {
echo 'Person does not exist, creating!';
}
$person = new TestPerson;
$person->name = 'Parent';
for ($i = 5; $i > 0; $i--) {
$child = new TestPerson;
$child->name = 'Child' . $i;
$person->addRelated('children', $child, 'mother');
$comPerson = new TestPersonComposite;
$comPerson->firstName = 'Com';
$comPerson->lastName = 'Person' . $i;
$person->addRelated('stepChildren', $comPerson, 'father');
}
$person->save(false);
CVarDumper::dump(array('person' => $person->object->data), 10, true);
}
}
<?php
/**
* @property string $name
* @property TestPerson $father
* @property TestPerson $mother
* @property TestPerson[] $children
* @property TestPersonComposite[] $stepChildren
*/
class TestPerson extends \ext\activedocument\Document {
public function relations() {
return array_merge(parent::relations(), array(
'father' => array(self::BELONGS_TO, 'TestPerson'),
'mother' => array(self::BELONGS_TO, 'TestPerson'),
'children' => array(self::HAS_MANY, 'TestPerson', 'nested' => true),
'stepChildren' => array(self::HAS_MANY, 'TestPersonComposite', 'order' => 'lastName ASC'),
));
}
}
<?php
/**
* @property string $firstName
* @property string $lastName
* @property TestPerson $parent
*/
class TestPersonComposite extends TestPerson {
public function primaryKey() {
return array('firstName', 'lastName');
}
public function relations() {
return array_merge(parent::relations(), array(
'parent' => array(self::BELONGS_TO, 'TestPerson'),
));
}
}
@intel352
Copy link
Author

Just a note, this example expects the page to be reloaded so that you can see fresh query results of the newly generated objects. In the case of someone using the Memory driver, you would always see your object(s) being created on every page load, due to the nature of the driver not persisting data outside of memory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment