Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
IIFE for setup script
<?php
/**
* What if we use an IIFE to guarantee scope control
* as well as aliasing and type hints for setup?
*/
// Standard setup script:
/**
* There's nothing really wrong with this, but you may wonder why alias $this to $installer.
* Also, what happens to the $entity var when the script is done?
* And while docblocks are nice, can we be sure that $installer is what we say it is?
*/
/** @var $installer Mage_Sales_Model_Entity_Setup */
$installer = $this;
$installer->startSetup();
$entity = array(
'entity_model' => 'example/foo',
'table' => 'example/foo',
);
$installer->addEntityType('foo', $entity);
...
$installer->endSetup();
// IIFE setup script
/**
* This function will fail noisily if its arguments don't match its type hints.
* That failure is a good thing – it's like a built in unit test.
* Also, any names defined within the function are scoped, so
* there's no question how they will be cleaned up.
*
* Even though an IIFE is closer to FP than OOP, it presents a clear
* interface to the programmer what values are available to work with.
*/
call_user_func(function(Mage_Eav_Model_Entity_Setup $installer, Varien_Db_Adapter_Interface $conn) {
$installer->startSetup();
$entity = array(
'entity_model' => 'example/foo',
'table' => 'example/foo',
);
$installer->addEntityType('foo', $entity);
$installer->endSetup();
}, $this, $conn);
// What about the setup class itself?
/**
* Well, I personally think the above example is too simple a case to
* justify defining a whole class around. Furthermore, even if you did
* you'd still have to register that class as the setup class and type hint
* it into the setup script. Then you'd still need to pass data to it from
* the setup script. The data is the risk here: Data housed anywhere other
* than the setup script itself (install or data-install) is difficult to
* reliably fix with an upgrade.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment