Zend Framework covers many day-to-day solutions and fits perfectly for most jobs, but if you\'re facing a challenge that\'s not yet covered in the framework, you can easily extend components to fit your needs. This way you still have the power of Zend Framework without having to re-write all from scratch.
9. How do we start ? <?php /** * @see Zend_Translate_Adapter */ require_once 'Zend/Translate/Adapter.php'; /** * MyComp_Translate_Adapter_Db * Translation adapter for using a database back-end * */ class Mycomp_Translate_Adapter_Db extends Zend_Translate_Adapter { }
10. load from database /** * Loads the translation data into the Adapter * @param string|array $data – DB related settings * - dbAdapter: adapter to connect with DB * - tableName: storage of the translation * - options: filter on the translations * @param string $locale – The locale this translation is for * @param array $options – general adapter options */ protected function _loadTranslationData($data, $locale, $options) { ... }
11. our custom logic // we create a select statement first $select = $options['dbAdapter']->select(); $select->from($data['tableName'], array($data['keyField'], $data['valueField'])) ->where('language = ?', $locale); $stmt = $select->query(); // we store our whole translation into $trData $trData = $stmt->fetchAll(); // we create a scheme to generate a Zend_Translate_Array type $trScheme = array (); if (!empty ($trData)) { foreach ($trData as $trEl) { $trScheme[$trEl[$data['keyField']]] = $trEl[$data['valueField']]; } }
12. putting it all back // we put everything back into data so it can be handled properly // by the translation adapter. $data = $trScheme; // we need to check if we don't call a clean up routine $options = array_merge($this->_options, $options); if (($options['clear'] == true) || !isset($this->_translate[$locale])) { $this->_translate[$locale] = array(); } // now we merge our data back to the translate adapter $this->_translate[$locale] = array_merge($this->_translate[$locale], $data); /** * NOTE: $this->_options and $this->_translate are properties * from the parent class Zend_Translate_Adapter */
13. finishing touch /** * returns the adapters name * * @return string */ public function toString() { return "Db"; }
14. using the new adapter // Setting up the translation parameters $data = array( 'dbAdapter' => $dbAdapter, // already set in the bootstrap 'tableName' => 'translation', 'localeField' => 'language', 'keyField' => 'key', 'valueField' => 'value', ); $options = array (); try { $translate = new Zend_Translate('MyComp_Translate_Adapter_Db', $data, 'en_US', $options); $translate->addTranslation($data, 'nl_BE', $options); $translate->addTranslation($data, 'fr_BE', $options); } catch (Zend_Translate_Exception $zte) { echo “<h1>” . $zte->getMessage() . “</h1>” . PHP_EOL; }
15. convenient view helper class MyComp_View_Helper_Tr { protected $_view; public function setView(Zend_View_Interface $view) { $this->_view = $view; } }