1

i've some questions on controllers structure for limiting duplicating code.

for example i want to retrieve men and woman. What's the best method to do this:

class User {

   public function men() {
       //render
   }

   public function women() {
       //render
   }

   //OR

   public function by_type($type) {
       //render
   }

}

It's a simple example but the number of type can grow. And each type can have seperate views. I'm searching for a scaling solution for the future. A best practice for this case of use.

Thanks

gotva
  • 5,919
  • 2
  • 25
  • 35
Fassbender
  • 121
  • 8
  • Create separate men and woman filter/view classes that implement the appropriate logic for each, and inject that filter/view into the `by_type` method of your User class – Mark Baker Nov 08 '13 at 09:20

2 Answers2

0

As far as I understand your question, you could call the function that really render the type inside the by_type function this way:

public function by_type($type) {
    if (method_exist($this, $type) {
        return call_user_func(array($this, $type));
    }
    else {
        throw new Exception('method do not exists!');
    }
}

This way you only need to write the method that render the type and call it using by_type method.

m4t1t0
  • 5,669
  • 3
  • 22
  • 30
0

Rails has a (somewhat controversial) principle called fat model, skinny controller, which basically means that you can use the controller to process logic for the views, and let the models handle the "heavy lifting" so-to-speak


CakePHP / Rails

To port from CakePHP to Rails, I would highly recommend looking at using the models as much as possible, as it allows you to create an application which utilizes the full performance structure of the server, and not just leave all the logic in the controllers, as is what many people do with CakePHP

Specifically for your issue:

#app/controllers/users_controller.rb
def index
    @user = User.gender(params[:gender])
end

#app/models/user.rb
def self.gender(type)
    where?("type = ?", type)
end

This allows you to keep your controller as thin as possible, thus allowing for the correct distribution of code throughout the application

I see Rails as a lot different than CakePHP, in that it helps you create really functional & content-rich applications that utilize the entire server, rather than just providing a layer to make a website dynamic

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147