Using ORM classes directly from the controller in MVC, bad practice?

前端 未结 4 2004
抹茶落季
抹茶落季 2021-01-12 13:06

I\'ve recently delved into using an ORM in my CodeIgniter application and one i\'ve gone for is Propel. Now this gives me the power to basically use Propels classes as the \

4条回答
  •  迷失自我
    2021-01-12 13:50

    With the Query classes Propel now uses, I think the difference with a more "formal" Model becomes smaller and smaller. If this will become a library that you release into the world it would be an advantage to have an abstraction layer so you can have different backends, but if it is an in-house application I would just use the Query classes as your Model.

    But remember that the Query classes are created to feel like an actual object, and that they hide the relational part as much as they can. You can use this to your advantage. Check out this article about rewriting your SQL queries with Query methods, especially the third answer: move more and more into your Query class, so your Controller doesn't feel like it uses a database.

    // Instead of this code in your controller,
    // tightly coupled to your database logic
    $books = BookQuery::create()
       ->filterByTitle('%war%')
       ->filterByPrice(array('max' => 10)
       ->filterByPublishedAt(array('max' => time()))
       ->leftJoin('Book.Author')
         ->where('Author.Name > ?', $fameTreshold);
    
    // You would use this code in your controller
    // and create small methods with the business logic in the BookQuery class
    $books = BookQuery::create()
      ->titleContainsWord('war')
      ->cheap()
      ->published()
      ->writtenByFamousAuthors();
    

提交回复
热议问题