Archive for the ‘Zend Framework’ Category

Using Zend Framework components separately

Sunday, August 7th, 2011

Did you have a situation when you are working on a project which is not using Zend Framework (ZF) and you need provide functionality which is already implemented within ZF? I did, and I do not like to reinvent a wheel. This is what I did:

Task: Automatically detect user preferred language and set proper month names for select box and proper currency sign.

What should be done:

1. Add needed component and dependencies into product structure –  the best way IMHO is create something called ‘lib’ directory and put there all third part library.

2. Setup autoloader for ZF.

set_include_path(get_include_path() . PATH_SEPARATOR . getcwd() . '/library');
require getcwd() . '/library/Zend/Loader/Autoloader.php';

$autoloader = Zend_Loader_Autoloader::getInstance();

If your additional libraries does not have commons namespaces structure you can use:

$autoloader->setFallbackAutoloader(true)

or write your own autoloader and register it by pushAutoloader method.

3. Use ZF as you like:

$locale = new Zend_Locale();
echo 'Language: ' . $locale->getLanguage() . '<br />';   //return da_DK
$list = $locale->getTranslationList('Month', $locale);
var_dump($list);
string 'januar' (length=6)
string 'februar' (length=7)
string 'marts' (length=5)
string 'april' (length=5)
string 'maj' (length=3)
string 'juni' (length=4)
string 'juli' (length=4)
string 'august' (length=6)
string 'september' (length=9)
string 'oktober' (length=7)
string 'november' (length=8)
string 'december' (length=8)
$currency = new Zend_Currency($locale);

var_dump($currency->getShortName()); //return DKK
var_dump($currency->getName()); //return Dansk krone
var_dump($currency->getSymbol()); //return kr

P.S You should also add Currency.php and Currency directory to your lib dir (those are not listed at first point).