Is there a need to persist data in model for use in methods?
In my ZF project I have a model, wich has to address a large array stored in Zend_Registry. The array gets into the Registry from cache (not from database). Different methods of the model can use the array many times during request. Having in mind best practices and optimized performance, I am not sure if I should:
- apply a dedicated property for that and use it for some kind of cache
- just get the array from registry each time.
Example of dedicated property:
class Application_Model_Category {
private $_tree = null;
...
public function _getTree() {
if (!$this->_tree) {
$this->_tree = Zend_Registry::get('tree');
}
return $this->_tree;
...
public function methodOne() {
foreach ($this->_getTree() as $category) {
...
}
}
public function methodTwo() {
$tree = $this->_getTree();
foreach ($tree as $category) {
...
$count = count($tree);
}
}
...
}
Example of getting each time from registry:
class Application_Model_Category {
...
public function methodOne() {
foreach (Zend_Registry::get('tree') as $category) {
...
}
}
public function methodTwo() {
$tree = Zend_Registry::get('tree');
foreach ($tree as $category) {
...
$count = count($tree);
}
}
...
}
Do these ways have any differ开发者_如何学运维ences at all (like memory or cpu usage)? Or is the first method just a bit nicier looking?
I would definitely go with the first one. It's much easier to change in the future if necessary and it encapsulates the data fetching better. (Really in that sentence, the second thing is the cause of the first.)
Think about this:
What if later down the road you want to be able to pass in an argument to the constructor to allow overriding the behavior of fetching it from a registry? If you go with the first method, you only have to change the code in one place.
Also, with the first option, if you extend the class, the child class does not need knowledge of the workings of getTree. With the second way, it would also have a dependence on a registry.
Basically the first way marginally decreases coupling, which is good.
I don't believe that there is any performance issue one way or the other since the array is not actually being copied, just referenced.
However, for clarity and testing, I would add public getters/setters for the tree. Your getter can lazy-load from Zend_Registry
as you are doing, but at least allowing a public setter more clearly reflects the dependence and allows you to test with a mock tree.
Well, obviously the first method, will slow the processing, to near negligible, but it all depends on the functionality, you are trying to create. Your first method ensures the _tree
variable to be present to continue the processing, the second one does not as it is more likely to bring up an exception. I would recommend the 1st method, rather than the 2nd.
精彩评论