Skip to content

Instantly share code, notes, and snippets.

@pawlik
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pawlik/5c8588a528e9cb97ad34 to your computer and use it in GitHub Desktop.
Save pawlik/5c8588a528e9cb97ad34 to your computer and use it in GitHub Desktop.
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),
@marcinrogacki
Copy link

I pick no. 1 cus is safer. Lazy loading give no benefits (there is no heavy loading behind scene)

@michal-niedzwiedzki
Copy link

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.

@pawlik
Copy link
Author

pawlik commented Dec 9, 2014

@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