So basically I'm struggling between 2 methods of changing model data.
Method 1: (function changes it directly in the model data)
$this->Model->set($data);
$this->Model->changeSomeData();
Method 2: (function with input and output)
$data = $this->Model->data;
$newdata = $this->Model->changeSomeData($data);
$this->Model->set($newdata);
Can someone shine some light on this, on what to use and why?
Thanks
I'm sure this is a legacy issue with Cake 1.x where calling Model->set($data) was common practice. I would guess it happen because validate(), create() and save() needed to have the id or data assigned to the model.
As the code matured this practice became obsolete as save() would accept $data and also perform validation.
The problem here is that CakePHP merged the model and entity into a single class. A good database layout would separate model and entity. Which is what I think they're doing with Cake 3.x
Another problem is that Cake uses caches for model instances. It's possible that two unrelated classes could change a model's data because they share the same reference.
So I would strongly recommend method #2.
The code is easier to read, and easier to maintain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With