开发者

How to encapsulate web2py business logic?

开发者 https://www.devze.com 2023-03-25 00:45 出处:网络
I just found web2py a couple days ago, and have been reading the documentation and through the source of a few example applications. I want to start programming more in Python. It seems that my take o

I just found web2py a couple days ago, and have been reading the documentation and through the source of a few example applications. I want to start programming more in Python. It seems that my take on MVC is a little skewed from theirs [web2py community].

After learning and working with PHP (and the Kohana framework), I'm used to the thin controller - fat model principle, where all business logic is placed in the model and the controller does nothing more than delegate what methods to perform on the model, and then passes data onto the view for rendering. However, it seems that 99% of the applications I've seen for web2py have fat controllers (putting all business logic in the actions), and the models are nothing more than table/constraint definitions.

I'm pretty well set on my view of a model, and I would rather put the business logic in the models (for re-usability and DRY code) but I haven't seen any code online that does this, although, to be fair, I haven't found an ample amount of applications. Can somebody point me in the right direction.

To be clear, I would like to make my models actual classes and encapsulate all business logic and database interactions into explicit methods. Something along the lines of...

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 haven't found the right way开发者_运维问答 to do this.

I'm not very well rehearsed on web2py, but I know there are a lot of features. The DAL, for instance, seems to be a very powerful feature which is tightly integrated with other helpers. I wonder if splitting my business logic as stated above would limit any of these features?


I think part of the difference is that web2py uses a DAL (database abstraction layer) rather than an ORM. You might find this explanation helpful. As it points out, in some cases, computed fields or virtual fields may do what you want. Also, some of the methods defined in your example class would be quite simple DAL statements and would probably not be worth writing 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 -- whatever works best for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号