1

I just started creating a simple web application with cakePHP and was wondering if I could avoid code duplication in my actions. I have got two models and the corresponding controllers both contain the same actions (index, view, add, edit, delete) with marginally different code, e.g.:

Transaction controller

public function add() {
    if ($this->request->is('post')) {
        $this->Transaction->create();
        if ($this->Transaction->save($this->request->data)) {
            $this->Session->setFlash(__('The transaction has been saved.'));
            return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The transaction could not be saved. Please, try again.'));
        }
    }
}

The second controller would have the same add() action, only for a different model (i.e. replace transaction by e.g. trades).

So is there a way to avoid this kind of code duplication?

2 Answers 2

2

Components are for this specific purpose.

According to the CakePHP book:

Components are packages of logic that are shared between controllers. If you find yourself wanting to copy and paste things between controllers, you might consider wrapping some functionality in a component.

More Details: "Creating a Component"

Other:

You might also look at the CRUD Plugin by Friends Of Cake.

Sign up to request clarification or add additional context in comments.

Comments

0

There's probably multiple ways of avoiding duplication. One I can think of at the moment is to write a controller that your controllers inherit from, something like:

class BaseController extends AppController {
    protected $modelName = '';

    /*Make sure all methods in this model are protected, so users
    can't navigate to them */
    protected function add() {
         if($this->request->is('post')) {
             $this->{$this->$modelName}->create();

        //etc....
    }
}

class TransactionController extends BaseController {
    public function __construct ( $request = null , $response = null ) {
          $this->modelName = 'Transaction';
          parent::__construct($request, $response);
    }

    public function add() {
          parent::add();
    }
}

I generally don't do this kind of thing though. You could end up decreasing readability for not much payoff, or you may find that your controllers will start diverging as you get deeper into development.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.