Zend framework 06 - zend config, pdf, i18n, l10n, sessions

Post on 17-May-2015

2,750 views 0 download

Tags:

description

Zend_Config simplifies the access to, the use of, and writing of, configuration data within applications. The configuration data may come from a variety of media supporting hierarchical data storage. Adapters for Arrays, ini and XML files are provided.

transcript

Zend Framework

6. Zend_Config, PDF, i18n, l10n, Sessions

Tricode Professional Serviceswww.tricode.nl

Date: 27-03-2009Authors: Marcel Blok

Patrick van DisselSander van Beek

2

Zend_Config

Zend_Config simplifies the access to, the use of, and writing of, configuration data within applications.

The configuration data may come from a variety of media supporting hierarchical data storage. Adapters for Arrays, ini and XML files are provided.

3

Zend_Config

Zend_Config creates an object-oriented wrapper around the configuration data.

<?php

$config = new Zend_Config_Xml(

’/path/to/config.xml’

, ’staging’ // section to load

, false // disallow modification

);

echo $config->application->caching->enabled

4

Zend_Config

Zend_Config implements the Countable andIterator interfaces. This makes:- That count() can be used (provided by Countable)

- You can iterate over Zend_Config objects with foreach (provided by Iterator)

5

Zend_Config

Zend_Config support single inheritance that enables configuration data to be inherited from one section of configuration data into another.

This reduces or eliminates the need to duplicate configuration data for different purposes.

6

Zend_ConfigConfiguration inheritance example (XML):<?xml version="1.0" encoding="UTF-8"?><config> <production> <application> <debugging> <enabled>false</enabled> <showenvbox>false</showenvbox> </debugging> </application> </production> <staging extends="production"> <application> <debugging showenvbox=“true” /> </application> </staging> <development extends="staging"> <application> <debugging> <enabled value=“true” /> </debugging> </application></development></config>

7

Zend_ConfigThree ways to define XML config nodes:<?xml version="1.0" encoding="UTF-8"?><config> <production> <application>

<debugging> <enabled>false</enabled> <showenvbox>false</showenvbox> </debugging> </application> </production> <staging extends="production">

<application> <debugging showenvbox=“true” /> </application> </staging> <development extends="staging"> <application>

<debugging> <enabled value=“true” /> </debugging> </application> </development></config>

8

Zend_Config

Return typeConfiguration data read into Zend_Config are always returnedas strings. Conversion of data from strings to other types is

leftto developers to suit their particular needs.

Write configuration data to file (ZF v1.7+)For each default Zend_Config adapter is a writer provided:- Zend_Config_Writer_Xml- Zend_Config_Writer_Ini- Zend_Config_Writer_Array

$writer = new Zend_Config_Writer_Xml();$writer->write(‘config.xml’, $config);

9

Zend_Config

Read-onlyZend_Config objects are read-only by default. The only way to make Zend_Config objects writable, is overriding this functionality in the constructor.

<?php$config = new Zend_Config_Xml(

’/path/to/config.xml’, ’staging’ // section to load, true // allow modification

);if (false === $config->readOnly()) {

$config->setReadOnly();}

10

Zend_Pdf

Features• Create a new document or load existing one. [2] • Retrieve a specified revision of the document. • Manipulate pages within a document. Change page order,

add new pages, remove pages from a document. • Different drawing primitives (lines, rectangles, polygons,

circles, ellipses and sectors). • Text drawing using any of the 14 standard (built-in) fonts

or your own custom TrueType fonts. • Rotations. • Image drawing. [3] • Incremental PDF file update.

[2] Loading PDF V1.4 (Acrobat 5) documents is now supported.

[3] JPG, PNG [Up to 8bit per channel+Alpha] and TIFF images are supported.

11

Zend_Pdf

// Create a new PDF document$pdf1 = new Zend_Pdf();

// Load a PDF document from a file$pdf2 = Zend_Pdf::load($fileName);

// Load a PDF document from a string$pdf3 = Zend_Pdf::parse($pdfString);

// Save PDF to a file, $updateOnly = false$pdf3->save($fileName, false);

// Render PDF as string, $newSegmentOnly = false $pdfString = $pdf3->render(false);

12

Zend_Pdf

Zend_Pdf contains 87 class files, spread over 24 folders with a total size of +/- 1MB (ZF v1.7.6)

This includes the 14 fonts that are build into the PDF standard:

• Courier (normal, bold, bold oblique, oblique)• Helvetica (normal, bold, bold oblique, oblique)• TimesRoman (normal, bold, bold oblique, oblique)• Symbol• ZapfDingbats

Also a way to use TrueType and CID (Character Identifier Font)

fonts is provided

13

Zend_Pdf

Pros• Very extended support for the features of PDF

1.4• Very Object OriëntedCons• Uses the closed PDF 1.4 standard

(instead of the open PDF 1.7 standard)

• The not OO-parts are not strictly checked• Focused on content of specific pages, instead of

the whole document(eg. elements do not stretch to the size of their content, and do not automaticly stretch over pages)

14

TCPDF

• 14 font files (194KB)• 4 php “class”/data files (730KB)• 1 php config file (6KB)Total 930KB (tcpdf v4.5.032)

Features• The same or comparable with Zend_Pdf• Uses the open PDF 1.7 standard

15

TCPDF// create new PDF document $pdf = new TCPDF(

PDF_PAGE_ORIENTATION, PDF_UNIT // User measure unit, PDF_PAGE_FORMAT, true // Output in unicode, ’UTF-8’ // Encoding, false // Use temp file caching

);// close and output PDF document// $destination = ‘I’; // Inline to the browser// $destination = ‘D’; // Browser, force download// $destination = ‘F’; // Save to a local file// $destination = ‘S’; // Return as a string$pdf->Output(‘example_001.pdf’, ’I’);

16

TCPDF

$colorBlack = array(51, 51, 51); // #333$pdf->SetTextColorArray($colorBlack);$pdf->SetFillColorArray($colorBlack);$pdf->SetDrawColorArray($colorBlack);$pdf->SetFont($pdf->getFontFamily(), ‘B’, 15);

// Set starting point$pdf->setY(20);$pdf->setX(120);$pdf->MultiCell(

100, 2 // width, height, ‘text’, 0, ‘L’ // no-border, text-align: Left, 0 // no background, 1, // to the beginning of the next line

);// MultiCell has 7 more parameters that can be set!

17

TCPDF

Pros• Uses the open PDF 1.7 standard• Very extended support for the features of PDF

1.7• Focused on the whole PDF document• Elements stretch automaticly with content• Elements stretch automaticly over pagesCons• (almost) No Object Oriëntation• PHP4 based (slowly switching to PHP5)

• No naming convention or coding standard used

18

Zend_Locale

• Zend_Locale is the Frameworks answer to the question, "How can the same application be used around the whole world?"

• Different regions will have different conventions for first names, surnames, salutory titles, formatting of numbers, dates, times, currencies, etc.

19

Internationalization (I18n)

Internationalization refers to support for use ofsystems, regardless of special needs unique togroups of users related by language, region,number format conventions, financial

conventions,time and date conventions, etc.

20

Localization (L10n)

Localization involves adding explicit support tosystems for special needs of these unique groups,such as language translation, and support for

localcustoms or conventions for communicating

plurals,dates, times, currencies, names, symbols, sortingand ordering

21

L10n & I18n

Zend Framework provides support for L10n & I18nthrough a combination of components, including:

• Zend_Locale, • Zend_Date, • Zend_Measure, • Zend_Translate, • Zend_Currency• Zend_TimeSync

22

What is a locale ?

• A locale string or object identifying a supported locale gives Zend_Locale and its subclasses access to information about the language and region expected by the user. Correct formatting, normalization, and conversions are made based on this information.

23

Locale representation

• Locale identifiers consist of information about the user's language and preferred/primary geographic region (e.g. state or province of home or workplace).

• The locale identifier strings used in Zend Framework are internationally defined standard abbreviations of language and region, written as language_REGION.

• Both the language and region parts are abbreviated to alphabetic characters.

24

Locale representation

Examples:

• A user from USA would expect the language English and the region USA, yielding the locale identifier "en_US"

• A user in Germany would expect the language German and the region Germany, yielding the locale identifier "de_DE".

25

Zend Locale

Zend_Locale will try to automatically select thecorrect locale:

1. From the users browser2. From the environment (server)3. From Zend Framework

You can manually specify to use one of theseMethods, or manually set the correct locale.

26

Default locale

Since Zend Framework Release 1.5 there is a good

way to handle defauklt locales. You can set adefault locale which the static setDefault()method. Of course, every unknown or not fullqualified locale will also throw an exception.setDefault() should be the first call before youinitiate any class using Zend_Locale.

27

Default locale

Example

// within the bootstrap file

Zend_Locale::setDefault(‘nl_NL');

// within your model/controller

$date = new Zend_Date();

28

ZF Locale-aware classes

• Be aware that all Locale-aware classes will automatically select the locale. So set the default as soon as possible!

• You can specify a specific locale to these classes:

$usLocale = new Zend_Locale('en_US');

$date = new Zend_Date('2006', Zend_Date::YEAR, $usLocale);

$temp = new Zend_Measure_Temperature('100,10', Zend_Measure::TEMPERATURE, $usLocale);

29

Application wide locale

You simply set an instance of Zend_Locale to theregistry with the key 'Zend_Locale'. Then thisinstance will be used within all locale aware

classesof Zend Framework. This way you set one localewithin your registry and then you can forget aboutsetting it again. It will automatically be used in allother classes.

30

Zend_Currency

“Zend_Currency is part of the strong support for i18n

in Zend Framework. It handles all issues related to

currency, money representation and formatting. Italso provides additional methods which providelocalized information on currencies, such as whichcurrency is used in which region.”

31

Using Zend_Currency

• Zend_Currency uses the default Locale

• Since a locale may include several currencies (or you want a different one), you can specify the desired currency.

• To use a different locale, you may specify this when instantiating Zend_Currency

32

Using Zend_Currency

Examples:

// expect standard locale 'de_AT'

// creates an instance from 'en_US' using default 'USD'

// currency for 'en_US‘

$currency = new Zend_Currency('en_US');

// creates an instance from the set locale ('de_AT') 

// using 'EUR' as currency

$currency = new Zend_Currency();

// creates an instance using 'EUR' as currency, 'en_US‘

// for number formatting

$currency = new Zend_Currency('en_US', 'EUR');

33

Creating an output string

Using it is easy:

// creates an instance with 'en_US' using 'USD', which is the de// default values for 'en_US‘$currency = new Zend_Currency('en_US');

// prints '$ 1,000.00‘echo $currency->toCurrency(1000);

// prints '$ 1.000,00‘echo $currency->toCurrency(1000, array('format' => 'de_AT'));

// prints '$ ١٬٠٠٠٫٠٠‘echo $currency->toCurrency(1000, array('script' => 'Arab'));

34

Zend_Currency options

You may change the default options of a locale / currency:

• Position Position of the currency symbol• Script Script used (latin, arab, etc.)• Format Format of the numbers (separator)• Display What to use symbol or name• Precision Decimal numbers to use• Name Currency name to use• Currency International abbreviation to use• Symbol Currency symbol to use

35

More examples

// creates an instance with 'en_US' using 'USD', 'Latin' and // 'en_US' as these are the default values from 'en_US‘$currency = new Zend_Currency('en_US');

// prints 'US$ 1,000.00‘echo $currency->toCurrency(1000);

$currency>setFormat(array('display' => Zend_Currency::USE_NAME,                      'position' => Zend_Currency::RIGHT));

// prints '1.000,00 US Dollar‘echo $currency->toCurrency(1000);

$currency->setFormat(array('name' => 'American Dollar'));// prints '1.000,00 American Dollar‘echo $currency->toCurrency(1000);

$currency->setFormat(array('format' => '##0.00'));// prints '1000,00 American Dollar‘echo $currency->toCurrency(1000);

36

Zend_Currency reference methods

To get information for a specific Locale use:

• getSymbol() ‘$’• getShortName() ‘USD’• getName() ‘US Dollar’• getRegionList() array of all regions for

(specified) currency• getCurrencyList() array of used currency

in (specified) region

37

Zend_Translate

“Zend_Translate is Zend Framework's solution for

multilingual applications.”

38

Why use ZF and not PHP self?

• Supports multiple source formats• Thread-safe gettext• Easy and generic API• Detection of the user's standard language• Automatic source detection

39

Zend_Translate adapters

Zend_Translate is able to use different adapters that

can be used for translating strings:

• Array• CSV• Gettext• Ini• Tbx• Tmx

• Qt• Xliff• XmlTm• Create your own!

40

Usage

print "Example\n";print "=======\n";print "Here is line one\n";print "Today is the " . date("d.m.Y") . "\n";

Becomes:

$translate = new Zend_Translate('gettext', '/my/path/source-de.mo', 'de');

print $translate->_("Example") . "\n";print "=======\n";print $translate->_("Here is line one") . "\n";printf($translate->_("Today is the %1\$s") .  "\n", date('d.m.Y'));

41

Source files

A simple language file could look like this:

return array(    'message1' => 'Nachricht1',    'message2' => 'Nachricht2',    'message3' => 'Nachricht3');

It can be used as follows:

$translate = new Zend_Translate('array', 

'/path/to/myarray.php', 

'de');

42

Options

The following options can always be set:

• clear clear already read translations• disableNotices No notices for unavailable

translations• ignore prefix to ignore dirs and files• log Log to this Zend_Log instance• logMessage The message to write• logUntranslated Log all untranslated

strings/IDs• scan Type of scanning for files

43

Multiple languages

When working with different languages there are a

few methods which will be useful:

• getLocale() gets the current locale• setLocale() sets the current locale• isAvailable() checks if the diven locale is

available• getList() get all currently set

languages for an adapter

44

Examples

// returns the currently set language$actual = $translate->getLocale();

// you can use the optional parameter while translatingecho $translate->_("my_text", "fr");// or set a new language$translate->setLocale("fr");echo $translate->_("my_text");// refer to the base language// fr_CH will be downgraded to fr$translate->setLocale("fr_CH");echo $translate->_("my_text");

// check if this language existif ($translate->isAvailable("fr")) {   

// language exists}

45

Automatic handling of languages

The algorithm will search for the best fitting localedepending on the user's browser and yourenvironment.

// Let's expect the browser returns these language settings:

// HTTP_ACCEPT_LANGUAGE = "de_AT=1;fr=1;en_US=0.8";

// Best found fitting language is 'de' ('de_AT' will degrade)

$translate = new Zend_Translate(    'gettext',    'my_de.mo',    'auto',    array('scan' => Zend_Translate::LOCALE_FILENAME));

46

Automatic handling of languages

Zend_Translate can detect translation sourcesautomatically. So you don't have to declare eachsource file manually. You can let Zend_Translatedo this job and scan the complete directorystructure for source files.

The usage is quite the same as initiating a singletranslation source with one difference. You mustgive a directory which has to be scanned instead afile.

47

Automatic handling of languages

The language files can be detected by:

• Language through naming directories• Language through filenames

– Filename– File extension– Filename tokens

48

Zend_Session

• Wrapper / OO interface for PHP’s internal session handling ($_SESSION)

• Its possible to use a custom save handler

• Supports namespaces

• Automaticly serializes on save

49

Zend_Session (2)

• Accessing session data:

$namespace = new Zend_Session_Namespace();  echo $namespace->myAtrribute;

• Namespaces to avoid collisions between sessions

$authNamespace = new Zend_Session_Namespace('Zend_Auth');$authNamespace->user = "myusername";

$webServiceNamespace = new Zend_Session_Namespace('Some_Web_Service');$webServiceNamespace->user = "mywebusername";

50

Zend_Session (3)

Useful methods:

• sessionExists() • rememberMe(integer $seconds) • forgetMe() • destroy(bool $remove_cookie = true, bool

$readonly = true) • setSaveHandler(Zend_Session_SaveHandler_Int

erface $interface)

51

Session security

Prevent session hijacking/fixation:

• Regenerate the session id after authentication

• Secure cookie over HTTPS

• Bind session to the users IP and brower agent