How to encapsulate Web2py business logic?

I just found web2py a couple of days ago and read the documentation both through the source of several applications. I want to start programming in Python. It seems like my MVC trick is a bit skewed from their [web2py community].

After learning and working with PHP (and the Kohana framework), I got used to the subtle controller - the sensible principle, where all business logic is placed in the model, and the controller does nothing more than delegate which methods to execute on the model, and then passes the data to the presentation for rendering. However, it seems that 99% of the applications I've seen for web2py have fat controllers (putting all the business logic in action), and models are nothing more than table definitions and constraints.

I'm pretty good at my point of view on the model, and I would prefer to place business logic in the models (for reuse and DRY code), but I have not seen any code on the Internet that does this, although to be honest, I don't found a sufficient number of applications. Can someone point me in the right direction.

To be clear, I would like to make my models valid classes and encapsulate all business logic and interaction with databases in explicit methods. Something like lines ...

class Article(object): def get_article(self, id): # Retrieve article by id, using db instance pass def get_latest_articles(self, limit): # Retrieve latest articles pass def get_hot_articles(self, limit): # Retrieve hot articles, based on algorithm for "hot" pass def create_article(self, data): # Insert article pass def define_tables(self): # Define schema the web2py way pass 

I did not find the right way to do this.

I did not rehearse very well on web2py, but I know that there are many possibilities. DAL, for example, seems to be a very powerful feature that is tightly integrated with other helpers. I wonder if the separation of my business logic, as stated above, limits any of these functions?

+4
source share
1 answer

I believe that the difference is that web2py uses DAL (database abstraction layer) rather than ORM. You may find this explanation helpful. As he points out, in some cases, computed fields or virtual fields can do what you want. In addition, some of the methods defined in your class class will be fairly simple DAL statements and you probably shouldn't write methods for.

Of course, if you want, you can define classes and functions in your models (or modules) and simply call them from your controllers - which is best for you.

+2
source

All Articles