Hi,
I'm trying to learn how to use xPDO (and more about OOP in general) so please show mercy if I do something totally dumb.
I'm putting together a snippet/component with basic CRUD methods. I want to be able to use these methods through AJAX.
I started by adding a single document in manager (ajax.html).
Created a snippet with code:
$base_path = $modx->getOption('assets_path').'components/crudTest/';
$o = '';
$f = $base_path.'crudTest.php';
if (file_exists($f)) {
$o = include $f;
} else {
$modx->setLogTarget('ECHO');
$modx->log(modX::LOG_LEVEL_ERROR,'StoreFinder not found at: '.$f);
}
echo $o;
Snippet call was placed (uncached) in my doc (ajax.html)
Using
Bob's guide I was able to generate table xml schema and necessary classes and when I follow his examples I'm able to insert, select and edit my data.
I "post" my forms to ajax.html using jQuery and so far no problems.
I want to go further and wrap my code into a class where each method will be a different action (ie: add, save, delete, select).
I changed my snippet to:
$path = $modx->getOption('assets_path').'components/crudTest/';
$modx->addPackage('crudTest',$path . 'model/','prefix_');
$output = '';
$action = ($_POST['action']) ? filter_var($_POST['action'], FILTER_SANITIZE_STRING) : 'index';
//get the class file
$f = $modx->getOption('assets_path').'components/crudTest/crudTest.class.php';
if (file_exists($f)) {
include $f;
$o = new CrudTest($modx);
if (method_exists($o,$action)) {
$output = $o->{$action}();
return $modx->toJSON($output);
}
}
$output = array('response' => NULL, 'error' => array('Method not found'));
return $modx->toJSON($output);
In my class I do:
class CrudTest {
public $modx;
function __construct(&$modx) {
$this->modx = & $modx;
}
public function index() {
$data = array(
'response' => NULL,
'error' => array(),
'action' => 'index'
);
return $data;
}
/* only one method to keep it short */
public function save() {
if ($_POST) {
$fields = array(
'user_id' => $this->modx->user->get('id'),
'addedon' => time()
);
$save = $this->modx->newObject('crudTest', $fields);
$save->save($save);
} else {
$return = 'empty';
}
//
$data = array(
'response' => $return,
'error' => array(),
'action' => 'save'
);
return $data;
}
}
Here is the place where I'm stuck.
I'm not sure what I did wrong here but I'm not able to get any of xPDO methods to work in my class.
My $this->modx object returns NULL or I'm getting errors like:
<b>Fatal error</b>: Nesting level too deep - recursive dependency?
There is a problem with how I reference $modx object in my class for sure and especially how (or where) I register my package but I have no clue what I did wrong.
I would appreciate if somebody help me understand how to do this properly.
thanks.