Tablel-less models in CakePHP that provide records or act like “enums”

This short article will cover two scenarios, one where you’ll store complete records in a model without a database connection for that model and another solution for enum like data or simply constants that can be wrapped in a model as well to give them a meaning.

Full multi-field records in a model without a database:

We are going to use the ArraySource from the community maintained Datasources plugin for CakePHP. Make sure you pick the right branch from the repository. There is a master (CakePHP 1.3), 2.0 and 2.3 branch available. Chose the branch that matches your projects CakePHP version.

Define a connection to the datasource in your app/Config/database.php:

In your Country model make sure it is using the datasource config you’ve just created and fill the Country::$records property with records:

A solution for single fields, enum like data:

If you don’t use a DB table and entries are limited, it is always good to use constants because you can’t do a typo without causing an error somewhere and UserLevel::USER is much more clear than a random ‘user’ string somewhere that could mean anything. Another advantage of this is the situation when you have to update your application because you suddenly get a lot more user models. All you have to do is to refactor your model to use a table then.