phpmodel-view-controllercakephp-2.0

Automatically running an unrelated action in cakePHP application


I am working on a small application to provide quotes for custom products. It's my first cakePHP application.

Many of the fields for the products are calculated automatically when a product is added or saved. The calculations use valuse stored in the 'Rates' table to perform the operations. These 'Rates' can also be updated by the admin and have their own model, view and controller. However, when the Rates are updated I need all of the existing products to be re-calculated as if the user had been to /products/edit and clicked save.

I really don't know how to trigger this when the rates are saved to the database

here is my ProductsController edit function:

public function edit($id = null) {
    $this->Product->id = $id;
    if (!$this->Product->exists()) {
        throw new NotFoundException(__('Invalid product'));
    }
    if ($this->request->is('post') || $this->request->is('put')) {
        $this->loadModel('Rate', '1');
        
        $Od = $this->request->data['Product']['material_od'] / 2;
        $materialMass = $this->Rate->field('steel_mass') * $this->request->data['Product']['material_length'] * (pi() * $Od * $Od );
        $this->Product->saveField('material_mass', $materialMass);

        $materialCost = $materialMass * $this->Product->Material->field('cost', array('Material.id' => $this->request->data['Product']['material_id']));
        $this->Product->saveField('material_cost', $materialCost);

        $materialMarkupRate = $this->Rate->field('material_markup') + 1;
        $wasteMarkupRate = $this->Rate->field('waste_markup') + 1;

        $materialMarkupCost = $materialCost * $materialMarkupRate * $wasteMarkupRate;
        $this->Product->saveField('material_markup_cost', $materialMarkupCost);
        
        $setupCost = $this->request->data['Product']['number_tools'] * $this->Rate->field('tool_time') * $this->Rate->field('setup_rate');
        $this->Product->saveField('setup_cost', $setupCost);
        
        $cuttingCost = $this->request->data['Product']['cutting_time'] * $this->Rate->field('cutting_rate');
        $this->Product->saveField('cutting_cost', $cuttingCost);
        
        $machiningCost = $this->request->data['Product']['machining_time'] * $this->Rate->field('machining_rate');
        $this->Product->saveField('machining_cost', $machiningCost);
        
        $polishingCost = $this->request->data['Product']['polishing_time'] * $this->Rate->field('polishing_rate');
        $this->Product->saveField('polishing_cost', $polishingCost);
        
        if ($this->Product->save($this->request->data)) {
            $this->Session->setFlash(__('The product has been saved'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The product could not be saved. Please, try again.'));
        }
    } else {
        $this->request->data = $this->Product->read(null, $id);
    }
    $materials = $this->Product->Material->find('list');
    $this->set(compact('materials'));
}

and my RatesController edit function:

public function edit($id = null) {
    $this->Rate->id = $id;
    if (!$this->Rate->exists()) {
        throw new NotFoundException(__('Invalid rate'));
    }
    if ($this->request->is('post') || $this->request->is('put')) {
        if ($this->Rate->save($this->request->data)) {
            $this->Session->setFlash(__('The settings have been saved.  Please update your products.'));
            $this->redirect(array('controller' => 'products', 'action' => 'index'));
        } else {
            $this->Session->setFlash(__('The rate could not be saved. Please, try again.'));
        }
    } else {
        $this->request->data = $this->Rate->read(null, $id);
    }
}

How can I trigger the first one from the second one?


Solution

  • There are a couple of issues that will help you not only clear up what you are trying to do, but do it in a more efficient way. Currently, every time you call $this->Product->saveField you are hitting your database. If this is a small app used by few people, it won't matter much. However, you should get into the habit of writing good clean code. Your variable names are great! Easy to understand. I would first suggest calculating all of the values and then hitting the database like this:

    ...
        $this->loadModel('Rate', '1');
        $materialMarkupRate = $this->Rate->field('material_markup') + 1;
        $wasteMarkupRate = $this->Rate->field('waste_markup') + 1;
    
        $Od = $this->request->data['Product']['material_od'] / 2;
        // make sure you have a hidden id form in the view, otherwise you will need to set it here
        $this->request->data['Product']['material_mass'] = $this->Rate->field('steel_mass') * $this->request->data['Product']['material_length'] * (pi() * $Od * $Od );
        $this->request->data['Product']['material_cost'] = $materialMass * $this->Product->Material->field('cost', array('Material.id' => $this->request->data['Product']['material_id']));
        $this->request->data['Product']['material_markup_cost'] = $materialCost * $materialMarkupRate * $wasteMarkupRate;
        $this->request->data['Product']['setup_cost'] = $this->request->data['Product']['number_tools'] * $this->Rate->field('tool_time') * $this->Rate->field('setup_rate');
        $this->request->data['Product']['cutting_cost'] = $this->request->data['Product']['cutting_time'] * $this->Rate->field('cutting_rate');
        $this->request->data['Product']['machining_cost'] = $this->request->data['Product']['machining_time'] * $this->Rate->field('machining_rate');
        $this->request->data['Product']['polishing_cost'] = $this->request->data['Product']['polishing_time'] * $this->Rate->field('polishing_rate');
    
        if ($this->Product->save($this->request->data)) {
    ...
    

    Second, if you need to call this method from other locations, that is a sign that you need to move it. Because this is data, you should move it to the Model.

    However, if you are saying that everytime the rates change, EVERY product in the database needs to be updated, this is still going to be a problem. Maybe not now, but later down the road. Think about having a 100MM records. You change one thing on the rates and you are churning on the database for a LONG time. That's a lot of resources.

    My advice is the change this and move it to the onFind callback in the ProductModel. The way it will work is every time you pull a record, it will run the math on the values before they are returned to the view. It is normally best NOT to store calculated values in the database. There are certain circumstances where you will want to, but in this case it seems you can calculate them on the fly. This will also prevent the need to recalculate every product every time the rate changes. It will also make for cleaner code.