3

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?

1
  • 1
    If you are already using a database I would create a table for this static data set. Your database won't mind and it's a lot "cleaner" than "faking" a table with an array. Commented Jun 15, 2010 at 22:37

2 Answers 2

4

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

About "in the DataSource"... Where is it (path)? what file do i edit with this function read() above ? It seems to me its a controller function, but i am not sure.
Please read the linked manual chapter about custom datasources.
The link in the answer is broken. Can someone provide the working link?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.