30 de abril de 2011

Total control over your models

Every single web2py application that uses database, has its own models dir.

This directory is particularly important due to some characteristics:
  1. models directory files ares executed in alphabetical order;
  2. Your application's database tables definitions stay in it;
  3. Objects defined by these files become available on your app's global scope. They can be accessed by controllers and views.
I warn you to pay attention to the first one: files are executed in alphabetical order.

Some newbies have dificulties with that, and tend to think this is strange. I did it, until I concluded this is the most intuitive way to things work. It gives me freedom to organize my app.

However, to avoid some mistakes this way can bring to your app, we need to adopt a clear and fool proof convetion to name models files.

I use this simple and efficient structure:
  1. models/0_db.py
  2. models/1_menu.py
  3. models/5_models.py
  4. models/5_validators.py
I rename the automatically created db.py file to 0_db.py. So, I guarantee all basic definitions are executed before anything else. The DAL object, who provides all data access funcionalities, is created in this script.

I also rename menu.py to 1_menu.py forcing all menu definitions to be executed after DAL object instantiation.

With these modified names, I'm sure that all the code I'll develop will be executed after the scaffolding app web2py generated to me.

From that point I write models/5_models.py with my table definitions. Nothing but db.define_table() commands.

Validators are written in models/5_validators.py. But, why separated from model definitions? First, because web2py recommends you don't mix validators with  db.define_table(). Second, because at this point I'm certain all tables are already created and all cross references between them will work with no need to adjust definition sequences. Sometimes it messes my scripts.

When I have many tables, I can separate them in various scripts, i.e, 5_models_accounts.py, 5_models_finances.py, etc. And, the same way, their validators.

Here, your creativity can fly, but remeber some principles:
Explicit is better than implicit.
Simple is better than complex.
Flat is better than nested.
Readabilty counts.
In the face of ambiguity, refuse the temptation to guess.

2 comentários: