tags:

views:

50

answers:

2

The CakePHP Cookbook states that a Model can use a file (csv for example) instead of an actual database table but I couldn't find any implementation for it.

I was wondering if it is possible to use an Array of data as a model in CakePHP since I have a fairly static set of data which is important to me in a relationship with another table but it doesn't make a whole lot of sense to create a complete table for it.

Is it possible to implement a CakePHP Model using an Array?

+3  A: 

It should be trivial to implement using a custom DataSource. You only need to implement a handful of methods in it for reading and/or writing data, which you can just get from an array. Since every method gets passed the model instance as its first parameter, you can keep the actual data in the model:

class MyModel extends AppModel {
    public $useDbConfig = 'array';
    public $staticData = array( /* data here */ );
}



// in the DataSource:
public function read($model, $queryData = array()) {
    $data = $model->staticData;
    // do something with $data
}
deceze
+1  A: 

If you want you can use http://github.com/jrbasso/array_datasource which is a datasource for mapping models to array data that will allow you to relate those models to database based models transparently.

This lets you use an array source as a model without needing to do anything besides provide the array data and set the datasource name in the model.

Read the docs for some examples - it is really quite easy to use and the code is easy to understand. It also allows you to do normal find* operations on the model, conditions etc.

Abba Bryant
thanks for the accept
Abba Bryant