Last active
August 29, 2015 14:11
-
-
Save pawlik/5c8588a528e9cb97ad34 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
goal: give helper A possibility to inject 'tax helper', if none injected - Mage::helper('tax') should be used by default. | |
both ways work: | |
1) | |
```php | |
/** | |
* @var Mage_Tax_Helper_Data | |
*/ | |
protected $_taxHelper; | |
public function __construct() | |
{ | |
$this->_taxHelper = Mage::helper('tax'); | |
} | |
public function setTaxHelper(Mage_Tax_Helper_Data $helper) | |
{ | |
$this->_taxHelper = $helper; | |
} | |
public function getTaxHelper() | |
{ | |
return $this->_taxHelper; | |
} | |
``` | |
and | |
2) | |
```php | |
/** | |
* @var Mage_Tax_Helper_Data | |
*/ | |
protected $_taxHelper; | |
// constructor not needed anymore | |
// public function __construct() | |
// { | |
// $this->_taxHelper = Mage::helper('tax'); | |
// } | |
public function setTaxHelper(Mage_Tax_Helper_Data $helper) | |
{ | |
$this->_taxHelper = $helper; | |
} | |
public function getTaxHelper() | |
{ | |
if(null === $this->_taxHelper) { | |
$this->_taxHelper = Mage::helper('tax'); | |
} | |
return $this->_taxHelper; | |
} | |
``` | |
2) looks familiar - because it's lazy loading pattern. 1) is safer, because it's possible to use `$this->_taxHelper` internally (should't care in non-test scenarios that it's not initialized). | |
(I'll stick to 1) because it means less changes in the original code - but I'm interested in your opinion), |
Use common sense. If helper initialization is expensive, leave it out. If its use is pervasive, go for eager loading.
One general rule should be: if a private/protected fields has a public accessor method always use the method.
@marcinrogacki: this could be heavy in tests (looks what happens in Mage_Tax_Helper_Data constructor $this->_app = !empty($args['app']) ? $args['app'] : Mage::app();
in unit tests this is sloooow ;)
@Stronger One general rule should be: if a private/protected fields has a public accessor method always use the method.
there's public getTaxHelper
- but still safe with 1) approach (unless someone overwrites __construct and forgets parent::__construct()... but this is another story)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I pick no. 1 cus is safer. Lazy loading give no benefits (there is no heavy loading behind scene)