Here is some example code for parsing a schema in MODX 2.x:
Let’s assume we choose a packagename “somepackage”.
- Create a schema under
core/components/somepackage/model/schema/somepackage.mysql.schema.xml
with the content:
<?xml version="1.0" encoding="UTF-8"?>
<model package="somepackage" baseClass="xPDOObject" platform="mysql" defaultEngine="InnoDB" version="1.1">
<object class="somepackageTest" table="somepackage_test" extends="xPDOSimpleObject">
<field key="some_field" dbtype="varchar" phptype="string" precision="100" null="false" default="" />
</object>
</model>
- To parse the schema, create a snippet with code like this:
<?php
$package_name = "somepackage";
$core_path = $modx->getOption('core_path', null, MODX_CORE_PATH ); // Path to 'core' folder
$model_folder = $core_path . 'components/' . $package_name . '/model/'; // Path where the generated class files should be saved to.
$schema_path = $core_path . 'components/' . $package_name . '/model/schema/' . $package_name . '.mysql.schema.xml'; // Path to your schema file
$manager = $modx->getManager();
$generator = $manager->getGenerator();
$success = $generator->parseSchema($schema_path, $model_folder);
if ($success){
return 'schema successfully parsed.';
} else {
return 'error parsing the schema.';
}
Run the snippet once. This should create the class files in core/components/somepackage/model/somepackage/
.
- To create the database table from the class files, create a snippet with code like this:
<?php
$package_name = "somepackage";
$core_path = $modx->getOption('core_path', null, MODX_CORE_PATH );
$modx->addPackage($package_name, $core_path . 'components/' . $package_name . '/model/');
$manager = $modx->getManager();
$success = $manager->createObjectContainer('somepackageTest');
if ($success){
return 'table successfully created.';
} else {
return 'error creating the table.';
}
Run the snippet once. This should create the database table modx_somepackage_test
.
- To use your class, create snippets with code like this:
To create a new entry:
<?php
$package_name = "somepackage";
$core_path = $modx->getOption('core_path', null, MODX_CORE_PATH );
$modx->addPackage($package_name, $core_path . 'components/' . $package_name . '/model/');
$new_object = $modx->newObject('somepackageTest');
$new_object->set('some_field', 'some value');
if ($new_object->save()) {
return 'new row successfully created.';
} else {
return 'error creating new row.';
}
To output the table content:
<?php
$package_name = "somepackage";
$core_path = $modx->getOption('core_path', null, MODX_CORE_PATH );
$modx->addPackage($package_name, $core_path . 'components/' . $package_name . '/model/');
$rows = $modx->getCollection('somepackageTest');
$output = '';
foreach ($rows as $row) {
$output .= '<pre>' . print_r($row->toArray(), 1) . '</pre>';
}
return $output;