W skryptach widoków często potrzebne jest przeprowadzanie złożonych funkcji: na przykład formatowanie daty, generowanie elementów formularzy, czy wyświetlanie odnośników akcji. Możesz użyć klas helperów w tym celu.
Klasa helpera jest prostą klasą. Powiedzmy, że potrzebujemy klasę
helpera o nazwie 'fooBar'. Domyślnie nazwa klasy jest poprzedzona
przedrostkiem 'Zend_View_Helper_'
(możesz określić własny
przedrostek podczas ustawiania ścieżki do klas helperów), a ostatni
segment nazwy klasy jest nazwą klasy helpera; ten segment powinien
być w postaci TitleCapped; pełna nazwa klasy wygląda więc tak:
Zend_View_Helper_FooBar
. Ta klasa powinna zawierać
przynajmniej jedną metodę, nazwaną tak jak klasa helpera, ale już w
postaci camelCased: fooBar()
.
Zwróć uwagę na wielkość liter
Nazwy klas helperów są zawsze w postaci camelCased, czyli nigdy nie zaczynają się wielką literą. Nazwa klasy jest w postaci MixedCased, ale wywoływana metoda zawsze ma postać camelCased.
Domyślne ścieżki helperów
Domyślna ścieżka helperów zawsze wskazuje na ścieżkę helperów
widoków Zend Framework np., 'Zend/View/Helper/'. Nawet jeśli
wywołasz metodę setHelperPath()
aby nadpisać istniejące
ścieżki, domyślna ścieżka zawsze będzie ustawiona aby być pewnym, że
domyślne helpery będą zawsze działać.
Aby użyć helpera w swoim skrypcie widoku, wywołaj go za pomocą
$this->nazwaHelpera()
. Obiekt Zend_View
załaduje klasę Zend_View_Helper_NazwaHelpera
, utworzy
obiekt tej klasy i wywoła metodę nazwaHelpera()
.
Instancja obiektu istnieje teraz w instancji Zend_View
i
będzie ona ponownie używana przy następnych wywołaniach
$this->nazwaHelpera()
.
Zend_View
posiada wbudowany zbiór klas helperów, z
których większość odnosi się do generowania formularzy, a każda z
nich automatycznie filtruje dane wyjściowe. Dodatkowo dostępne są
klasy helperów służące do tworzenia adresów URL na podstawie tras,
do tworzenia list HTML oraz do deklarowania zmiennych. Obecnie
dostępne klasy helperów to:
declareVars():
Głównie używana gdy używamy metodystrictVars()
, ta klasa helpera może być użyta do zadeklarowania zmiennych szablonu, które zostały ustawione lub nie, w obiekcie widoku. Możemy też użyć jej do ustawienia domyślnych wartości. Tablice przekazane do metody jako argumenty zostaną użyte do ustawienia domyślnych wartości; w przeciwnym razie, gdy zmienna nie istnieje, zostanie ustawiona jako pusty łańcuch znaków.fieldset($name, $content, $attribs):
Tworzy element fieldset. Jeśli tablica$attribs
zawiera klucz 'legend', ta wartość zostanie użyta jako legenda pola fieldset. Pole fieldset będzie zawierać zawartość przekazaną do tego helpera przez zmienną$content
.form($name, $attribs, $content):
Generuje formularz. Wszystkie atrybuty z tablicy$attribs
będą zabezpieczone i renderowane jako atrybuty XHTML znacznika form. Jeśli przekazana jest zmienna$content
i ma inną wartość niż false, to zawartość tej zmiennej zostanie renderowana wraz ze znacznikiem otwierającym i zamykającym formularz; jeśli zmienna$content
ma wartość false (domyślnie), zostanie zrenderowany tylko znacznik otwierający.formButton($name, $value, $attribs):
Tworzy element <button />.-
formCheckbox($name, $value, $attribs, $options):
Tworzy element <input type="checkbox" />.Domyślnie, jeśli zmienne $value oraz $options nie są przekazane, dla pola niezaznaczonego zostanie przyjęta wartość '0', a dla zaznaczonego wartość '1'. Jeśli zostanie przekazana zmienna $value, ale nie zostanie przekazana zmienna $options, dla pola zaznaczonego zostanie przyjęta wartość zmiennej $value.
Zmienna $options powinna być tablicą. Jeśli tablica jest indeksowana, dla pola zaznaczonego zostanie przyjęta pierwsza wartość, a druga wartość dla pola niezaznaczonego; wszystkie inne wartości zostaną zignorowane. Możesz także przekazać tablicę asocjacyjną z kluczami 'checked' oraz 'unChecked'.
Jeśli zmienna $options zostanie przekazana, a wartość $value jest równa wartości określonej dla pola zaznaczonego, to element zostanie zaznaczony. Możesz także określić czy element ma być zaznaczony przekazując logiczną wartość dla atrybutu 'checked'.
Powyższe najlepiej podsumować za pomocą przykładów:
// '1' oraz '0' jako opcje dla pola zaznaczonego/niezaznaczonego; // pole jest niezaznaczone echo $this->formCheckbox('foo'); // '1' oraz '0' jako opcje dla pola zaznaczonego/niezaznaczonego; // pole jest zaznaczone echo $this->formCheckbox('foo', null, array('checked' => true)); // 'bar' oraz '0' jako opcje dla pola zaznaczonego/niezaznaczonego; // pole jest niezaznaczone echo $this->formCheckbox('foo', 'bar'); // 'bar' oraz '0' jako opcje dla pola zaznaczonego/niezaznaczonego; // pole jest zaznaczone echo $this->formCheckbox('foo', 'bar', array('checked' => true)); // 'bar' oraz 'baz' jako opcje dla pola zaznaczonego/niezaznaczonego; // pole jest niezaznaczone echo $this->formCheckbox('foo', null, null, array('bar', 'baz'); // 'bar' oraz 'baz' jako opcje dla pola zaznaczonego/niezaznaczonego; // pole jest niezaznaczone echo $this->formCheckbox('foo', null, null, array( 'checked' => 'bar', 'unChecked' => 'baz' )); // 'bar' oraz 'baz' jako opcje dla pola zaznaczonego/niezaznaczonego; // pole jest zaznaczone echo $this->formCheckbox('foo', 'bar', null, array('bar', 'baz'); echo $this->formCheckbox('foo', null, array('checked' => true), array('bar', 'baz'); // 'bar' oraz 'baz' jako opcje dla pola zaznaczonego/niezaznaczonego; // pole jest niezaznaczone echo $this->formCheckbox('foo', 'baz', null, array('bar', 'baz'); echo $this->formCheckbox('foo', null, array('checked' => false), array('bar', 'baz');
We wszystkich przypadkach zostanie dołączony ukryty element z wartością dla pola niezaznaczonego; w ten sposób uzyskamy pewność, że nawet jeśli pole nie będzie zaznaczone, to do formularza zostanie przekazana poprawna wartość.
-
formErrors($errors, $options):
Generuje listę nieuporządkowaną zawierająca informacje o błędach. Zmienna$errors
powinna być łańcuchem znaków lub tablicą łańcuchów znaków; Zmienna$options
powinna zawierać atrybuty jakie chcesz umieścić w znaczniku otwierającym listę.Możesz określić alternatywny sposób otwarcia, zamknięcia i oddzielania informacji o błędach wywołując metody helpera:
setElementStart($string)
; domyślną wartością jest '<ul class="errors"%s"><li>', gdzie %s jest zastąpione atrybutami zdefiniowanymi w zmiennej$options
.setElementSeparator($string)
; domyślną wartością jest '</li><li>'.setElementEnd($string)
; domyślną wartością jest '</li></ul>'.
formFile($name, $value, $attribs):
Tworzy element <input type="file" />.formHidden($name, $value, $attribs):
Tworzy element <input type="hidden" />.formLabel($name, $value, $attribs):
Tworzy element <label>, nadając atrybutowifor
wartość zmiennej$name
i ustawiając jako etykietę wartość zmiennej$value
. Jeśli opcjadisable
zostanie przekazana w zmiennej$attribs
, żaden kod nie zostanie zwrócony.formMultiCheckbox($name, $value, $attribs, $options, $listsep):
Tworzy listę elementów checkbox. Zmienna$options
powinna być asocjacyjną tablicą, i może mieć dowolne rozmiary. Zmienna$value
może być pojedynczą wartością lub tablicą wartości, które odpowiadają kluczom tablicy$options
. Zmienna$listsep
jest separatorem elementów, domyślnie ma wartość <br />. Domyślnie ten element jest traktowany jako tablica; wszystkie pola mają te samą nazwę i będą wysłane jako tablica.formPassword($name, $value, $attribs):
Tworzy element <input type="password" />.formRadio($name, $value, $attribs, $options):
Tworzy serię elementów <input type="radio" />, po jednym dla każdego elementu tablicy $options. W tablicy $options, klucz jest wartością przycisku radio, a wartość elementu tablicy jest etykietą przycisku radio. Zmienna $value określa wartość przycisku, który ma być początkowo zaznaczony.formReset($name, $value, $attribs):
Tworzy element <input type="reset" />.formSelect($name, $value, $attribs, $options):
Tworzy blok <select>...</select>, z elementami <option> po jednym dla każdego elementu tablicy $options. W tablicy $options klucz jest wartością elementu, a wartość jest etykietą. Zmienna $value określa wartość elementu (lub elementów), który ma być początkowo zaznaczony.formSubmit($name, $value, $attribs):
Tworzy element <input type="submit" />.formText($name, $value, $attribs):
Tworzy element <input type="text" />.formTextarea($name, $value, $attribs):
Tworzy element <textarea>...</textarea>.url($urlOptions, $name, $reset):
Tworzy adres URL na podstawie nazwy trasy. Parametr$urlOptions
powinien być tablicą asocjacyjną zawierającą pary klucz/wartość używane przez daną trasę.htmlList($items, $ordered, $attribs, $escape):
generuje uporządkowane oraz nieuporządkowane listy na podstawie przekazanego do niej parametru$items
. Jeśli parametr$items
jest wielowymiarową tablicą, zostanie zbudowana lista zagnieżdżona. Jeśli flaga$escape
ma wartość true (domyślnie), każdy z elementów zostanie zabezpieczony za pomocą mechanizmu zarejestrowanego w obiekcie widoku; przekaż wartość false aby zezwolić na wyświetlanie kodu html wewnątrz elementów list.
Użycie tych metod w Twoim skrypcie jest bardzo łatwe, poniżej znajduje się przykład. Zauważ, że wszystko czego potrzebujesz to wywołanie tych metod; załadowanie ich i utworzenie instancji odbędzie się automatycznie.
// wewnątrz skryptu widoku, $this odnosi się do instancji Zend_View. // // załóżmy, że już przypisałeś serię elementów opcji jako tablicę // o nazwie $countries = array('us' => 'United States', 'il' => // 'Israel', 'de' => 'Germany'). ?> <form action="action.php" method="post"> <p><label>Adres Email: <?php echo $this->formText('email', 'you@example.com', array('size' => 32)) ?> </label></p> <p><label>Kraj: <?php echo $this->formSelect('country', 'us', null, $this->countries) ?> </label></p> <p><label>Czy zgadzasz się? <?php echo $this->formCheckbox('opt_in', 'yes', null, array('yes', 'no')) ?> </label></p> </form>
Rezultat wyglądałby w ten sposób:
<form action="action.php" method="post"> <p><label>Adres Email: <input type="text" name="email" value="you@example.com" size="32" /> </label></p> <p><label>Kraj: <select name="country"> <option value="us" selected="selected">United States</option> <option value="il">Israel</option> <option value="de">Germany</option> </select> </label></p> <p><label>Czy zgadzasz się? <input type="hidden" name="opt_in" value="no" /> <input type="checkbox" name="opt_in" value="yes" checked="checked" /> </label></p> </form>
Helper Action
pozwala skryptom widoku na uruchomienie
konkretnej akcji kontrolera; wynik wywołania znajdujący się w obiekcie
odpowiedzi zostaje zwrócony. Możemy go użyć gdy dana akcja generuje
zawartość, którą możemy wielokrotnie wykorzystać lub zawartość w rodzaju
wdigeta.
Akcje które wywołują metodę _forward()
lub przekierowują
będą uznane za nieprawidłowe i helper zwróci pusty łańcuch znaków.
Interfejs helpera Action
jest podobny jak w większości
komponentów MVC które wywołują akcje kontrolerów: action($action,
$controller, $module = null, array $params = array())
.
Parametry $action
oraz $controller
są wymagane;
jeśli moduł nie zostanie określony, przyjęty zostanie moduł domyślny.
Przykład 931. Proste użycia helpera Action
Przykładem może być kontroler CommentController
zawierający akcję listAction()
, którą chcesz wywołać
aby pobrać dla obecnego żądania listę komentarzy:
<div id="sidebar right"> <div class="item"> <?= $this->action('list', 'comment', null, array('count' => 10)); ?> </div> </div>
The Partial
view helper is used to render a specified
template within its own variable scope. The primary use is for reusable
template fragments with which you do not need to worry about variable
name clashes. Additionally, they allow you to specify partial view
scripts from specific modules.
A sibling to the Partial
, the PartialLoop
view
helper allows you to pass iterable data, and render a partial for each
item.
PartialLoop Counter
The PartialLoop
view helper assigns a variable to the view named
partialCounter which passes the current position of the array to
the view script. This provides an easy way to have alternating colors on table rows for
example.
Przykład 932. Basic Usage of Partials
Basic usage of partials is to render a template fragment in its own view scope. Consider the following partial script:
<?php // partial.phtml ?> <ul> <li>From: <?php echo $this->escape($this->from) ?></li> <li>Subject: <?php echo $this->escape($this->subject) ?></li> </ul>
You would then call it from your view script using the following:
<?php echo $this->partial('partial.phtml', array( 'from' => 'Team Framework', 'subject' => 'view partials')); ?>
Which would then render:
<ul> <li>From: Team Framework</li> <li>Subject: view partials</li> </ul>
What is a model?
A model used with the Partial
view helper can be
one of the following:
-
Array. If an array is passed, it should be associative, as its key/value pairs are assigned to the view with keys as view variables.
-
Object implementing toArray() method. If an object is passed an has a
toArray()
method, the results oftoArray()
will be assigned to the view object as view variables. -
Standard object. Any other object will assign the results of
object_get_vars()
(essentially all public properties of the object) to the view object.
If your model is an object, you may want to have it passed as an object to the partial script, instead of serializing it to an array of variables. You can do this by setting the 'objectKey' property of the appropriate helper:
// Tell partial to pass objects as 'model' variable $view->partial()->setObjectKey('model'); // Tell partial to pass objects from partialLoop as 'model' variable // in final partial view script: $view->partialLoop()->setObjectKey('model');
This technique is particularly useful when passing
Zend_Db_Table_Rowset
s to
partialLoop()
, as you then have full access to your
row objects within the view scripts, allowing you to call
methods on them (such as retrieving values from parent or
dependent rows).
Przykład 933. Using PartialLoop to Render Iterable Models
Typically, you'll want to use partials in a loop, to render the same content fragment many times; this way you can put large blocks of repeated content or complex display logic into a single location. However this has a performance impact, as the partial helper needs to be invoked once for each iteration.
The PartialLoop
view helper helps solve this issue. It
allows you to pass an iterable item (array or object implementing
Iterator) as the model. It then iterates over this,
passing, the items to the partial script as the model. Items in the
iterator may be any model the Partial
view helper
allows.
Let's assume the following partial view script:
<?php // partialLoop.phtml ?> <dt><?php echo $this->key ?></dt> <dd><?php echo $this->value ?></dd>
And the following "model":
$model = array( array('key' => 'Mammal', 'value' => 'Camel'), array('key' => 'Bird', 'value' => 'Penguin'), array('key' => 'Reptile', 'value' => 'Asp'), array('key' => 'Fish', 'value' => 'Flounder'), );
In your view script, you could then invoke the
PartialLoop
helper:
<dl> <?php echo $this->partialLoop('partialLoop.phtml', $model) ?> </dl>
<dl> <dt>Mammal</dt> <dd>Camel</dd> <dt>Bird</dt> <dd>Penguin</dd> <dt>Reptile</dt> <dd>Asp</dd> <dt>Fish</dt> <dd>Flounder</dd> </dl>
Przykład 934. Rendering Partials in Other Modules
Sometime a partial will exist in a different module. If you know the
name of the module, you can pass it as the second argument to either
partial()
or partialLoop()
, moving the
$model
argument to third position.
For instance, if there's a pager partial you wish to use that's in the 'list' module, you could grab it as follows:
<?php echo $this->partial('pager.phtml', 'list', $pagerData) ?>
In this way, you can re-use partials created specifically for other modules. That said, it's likely a better practice to put re-usable partials in shared view script paths.
The Placeholder
view helper is used to persist content
between view scripts and view instances. It also offers some useful
features such as aggregating content, capturing view script content
for later use, and adding pre- and post-text to content (and custom
separators for aggregated content).
Przykład 935. Basic Usage of Placeholders
Basic usage of placeholders is to persist view data. Each invocation
of the Placeholder
helper expects a placeholder name;
the helper then returns a placeholder container object that you can
either manipulate or simply echo out.
<?php $this->placeholder('foo')->set("Some text for later") ?> <?php echo $this->placeholder('foo'); // outputs "Some text for later" ?>
Przykład 936. Using Placeholders to Aggregate Content
Aggregating content via placeholders can be useful at times as well. For instance, your view script may have a variable array from which you wish to retrieve messages to display later; a later view script can then determine how those will be rendered.
The Placeholder
view helper uses containers that extend
ArrayObject
, providing a rich featureset for
manipulating arrays. In addition, it offers a variety of methods for
formatting the content stored in the container:
-
setPrefix($prefix)
sets text with which to prefix the content. UsegetPrefix()
at any time to determine what the current setting is. -
setPostfix($prefix)
sets text with which to append the content. UsegetPostfix()
at any time to determine what the current setting is. -
setSeparator($prefix)
sets text with which to separate aggregated content. UsegetSeparator()
at any time to determine what the current setting is. -
setIndent($prefix)
can be used to set an indentation value for content. If an integer is passed, that number of spaces will be used; if a string is passed, the string will be used. UsegetIndent()
at any time to determine what the current setting is.
<!-- first view script --> <?php $this->placeholder('foo')->exchangeArray($this->data) ?>
<!-- later view script --> <?php $this->placeholder('foo')->setPrefix("<ul>\n <li>") ->setSeparator("</li><li>\n") ->setIndent(4) ->setPostfix("</li></ul>\n"); ?> <?php echo $this->placeholder('foo'); // outputs as unordered list with pretty indentation ?>
Because the Placeholder
container objects extend
ArrayObject
, you can also assign content to a specific
key in the container easily, instead of simply pushing it into the
container. Keys may be accessed either as object properties or as
array keys.
<?php $this->placeholder('foo')->bar = $this->data ?> <?php echo $this->placeholder('foo')->bar ?> <?php $foo = $this->placeholder('foo'); echo $foo['bar']; ?>
Przykład 937. Using Placeholders to Capture Content
Occasionally you may have content for a placeholder in a view script
that is easiest to template; the Placeholder
view
helper allows you to capture arbitrary content for later rendering
using the following API.
-
captureStart($type, $key)
begins capturing content.$type
should be one of thePlaceholder
constantsAPPEND
orSET
. IfAPPEND
, captured content is appended to the list of current content in the placeholder; ifSET
, captured content is used as the sole value of the placeholder (potentially replacing any previous content). By default,$type
isAPPEND
.$key
can be used to specify a specific key in the placeholder container to which you want content captured.captureStart()
locks capturing untilcaptureEnd()
is called; you cannot nest capturing with the same placeholder container. Doing so will raise an exception. -
captureEnd()
stops capturing content, and places it in the container object according to howcaptureStart()
was called.
<!-- Default capture: append --> <?php $this->placeholder('foo')->captureStart(); foreach ($this->data as $datum): ?> <div class="foo"> <h2><?php echo $datum->title ?></h2> <p><?php echo $datum->content ?></p> </div> <?php endforeach; ?> <?php $this->placeholder('foo')->captureEnd() ?> <?php echo $this->placeholder('foo') ?>
<!-- Capture to key --> <?php $this->placeholder('foo')->captureStart('SET', 'data'); foreach ($this->data as $datum): ?> <div class="foo"> <h2><?php echo $datum->title ?></h2> <p><?php echo $datum->content ?></p> </div> <?php endforeach; ?> <?php $this->placeholder('foo')->captureEnd() ?> <?php echo $this->placeholder('foo')->data ?>
Zend Framework ships with a number of "concrete" placeholder implementations. These are for commonly used placeholders: doctype, page title, and various <head> elements. In all cases, calling the placeholder with no arguments returns the element itself.
Documentation for each element is covered separately, as linked below:
Poprawne dokumenty HTML oraz XHTML powinny zawierać deklarację typu
dokumentu DOCTYPE
. Oprócz tego, że wszystkie rodzaje
deklaracji trudno jest zapamiętać, to wyświetlanie niektórych elementów
w dokumencie może zależeć od jego typu (przykładowo, użycie CDATA w
elementach <script>
czy w elementach
<style>
).
Helper Doctype
pozwala ci na określenie jedno z
następujących typów:
XHTML11
XHTML1_STRICT
XHTML1_TRANSITIONAL
XHTML1_FRAMESET
XHTML_BASIC1
HTML4_STRICT
HTML4_LOOSE
HTML4_FRAMESET
Możesz określić także własny typ dokumentu o ile ma prawidłowy format.
Helper Doctype
jest implementacją
helpera Placeholder
.
Przykład 938. Podstawowe użycie helpera Doctype
Możesz określić typ dokumentu w dowolnej chwili. Jednak helpery których działania zależy od typu dokumentu mogą sprawdzić ten typ tylko pod warunkiem że go wcześniej określisz, więc najlepiej będzie jak określisz typ dokumentu w pliku uruchamiającym:
$doctypeHelper = new Zend_View_Helper_Doctype(); $doctypeHelper->doctype('XHTML1_STRICT');
I teraz wyświetl definicję typu dokumentu w swoim skrypcie layoutu:
<?php echo $this->doctype() ?>
Przykład 939. Pobieranie typu dokumentu
Jeśli potrzebujesz sprawdzić typ dokumentu, możesz to zrobić
wywołując metodę getDoctype()
obiektu, który jest
zwracany po wywołaniu helpera.
$doctype = $view->doctype()->getDoctype();
Najczęściej będzie potrzebował sprawdzić czy dany typ dokumentu jest
typem XHTML czy nie; do tego wystarczy metoda isXhtml()
:
if ($view->doctype()->isXhtml()) { // zrób coś w inny sposób }
Element HTML <link>
jest używany do dołączania różnego
rodzaju zasobów do dokumentu html: arkuszy stylów, kanałów informacyjnych,
ikon, adresów trackback i wielu innych. Helper HeadLink
zapewnia prosty interfejs służący do tworzenia i łączenia tych
elementów, a następnie do wyświetlenia ich później w skrypcie layoutu.
Helper HeadLink
posiada specjalne metody do dodawania
arkuszy stylów:
appendStylesheet($href, $media, $conditionalStylesheet)
offsetSetStylesheet($index, $href, $media, $conditionalStylesheet)
prependStylesheet($href, $media, $conditionalStylesheet)
setStylesheet($href, $media, $conditionalStylesheet)
Domyślną wartością zmiennej $media
jest 'screen', jednak
możemy nadać jej inną poprawną wartość. Zmienna
$conditionalStylesheet
jest wartością logiczną określającą
czy podczas renderowania powinien zostać dodany specjalny komentarz
zapobiegający ładowaniu arkusza stylów na określonych platformach.
Dodatkowo helper HeadLink
posiada specjalne metody
do obsługi łącz 'alternate':
appendAlternate($href, $type, $title)
offsetSetAlternate($index, $href, $type, $title)
prependAlternate($href, $type, $title)
setAlternate($href, $type, $title)
Metoda headLink()
helpera pozwala na określenie wszystkich
potrzebnych atrybutów elementu <link>
, a także
pozwala określić jego umiejscowienie -- czy nowy element ma zastąpić
wszystkie istniejące, dołączyć go na koniec lub na początek stosu.
Helper HeadLink
jest implementacją
helpera
Placeholder.
Przykład 940. Proste użycie helpera HeadLink
Możesz użyć helpera headLink
w dowolnym momencie.
Najczęściej będziesz określał globalne łącza w pliku layoutu,
a łącza specyficzne dla aplikacji w skryptach widoków. W skrypcie
layoutu wyświetlisz na koniec wszystkie łącza w sekcji
<head>.
<?php // ustawianie łącz w skrypcie widoku: $this->headLink()->appendStylesheet('/styles/basic.css') ->headLink(array('rel' => 'favicon', 'href' => '/img/favicon.ico'), 'PREPEND') ->prependStylesheet('/styles/moz.css', 'screen', true); ?> <?php // generowaie łącz: ?> <?= $this->headLink() ?>
Element HTML <meta>
używany jest do definiowania
informacji meta o dokumencie HTML -- zazwyczaj są to słowa kluczowe,
informacje o zestawie znaków, informacje o sposobie buforowania itp.
Są dwa rodzaje znaczników meta, 'http-equiv' oraz 'name', oba muszą
zawierać także atrybut 'content', a mogą dodatkowo zawierać jeszcze
atrybuty 'lang' oraz 'scheme'.
Helper HeadMeta
udostępnia następujące metody do ustawiania
i dodawania znaczników meta:
appendName($keyValue, $content, $conditionalName)
offsetSetName($index, $keyValue, $content, $conditionalName)
prependName($keyValue, $content, $conditionalName)
setName($keyValue, $content, $modifiers)
appendHttpEquiv($keyValue, $content, $conditionalHttpEquiv)
offsetSetHttpEquiv($index, $keyValue, $content, $conditionalHttpEquiv)
prependHttpEquiv($keyValue, $content, $conditionalHttpEquiv)
setHttpEquiv($keyValue, $content, $modifiers)
Zmienna $keyValue
jest używana do definiowania wartości
atrybutów 'name' oraz 'http-equiv'; Zmienna $content
definiuje wartość atrybutu 'content', a zmienna $modifiers
jest opcjonalną asocjacyjną tablicą, która może zawierać klucze dla
atrybutów 'lang' oraz 'scheme'.
Możesz także ustawić znaczniki meta używając metody headMeta()
helpera, która posiada następującą sygnaturę: headMeta($content,
$keyValue, $keyType = 'name', $modifiers = array(), $placement =
'APPEND')
.
Parametr $keyValue
jest zawartością dla klucza określonego
w parametrze $keyType
, którego wartością zawsze powinno być
'name' lub 'http-equiv'.
Parametr $placement
może mieć wartość 'SET' (nadpisuje
wszystkie wcześniej ustawione wartości), 'APPEND' (dodaje na spód stosu),
lub 'PREPEND' (dodaje na wierzchołek stosu).
Helper HeadMeta
nadpisuje każdą z metod append()
,
offsetSet()
, prepend()
, oraz set()
aby wymusić użycie specjalnych metod opisanych powyżej.
Wewnętrznie klasa przechowuje każdy element jako obiekt klasy
stdClass
, który jest potem serializowany za pomocą metody
itemToString()
.
Pozwala to na sprawdzenie elementów znajdujących się na stosie, a także
na zmianę wartości poprzez modyfikację zwróconego obiektu.
HelperHeadMeta
jest implementacją
helpera
Placeholder.
Przykład 941. Podstawowe użycie helpera HeadMeta
Możesz określić nowy znacznik meta w dowolnej chwili. Najczęściej będziesz określał zasady buforowania po stronie klienta oraz dane SEO.
Przykładowo, jeśli chcesz określić słowa kluczowe SEO, powinieneś utworzyć znacznik meta o nazwie 'keywords', a jego zawartością powinny być słowa kluczowe, które chcesz połączyć z daną stroną:
// ustawienie słów kluczowych $this->headMeta()->appendName('keywords', 'framework php productivity');
Jeśli chcesz ustalić zasady buforowania po stronie klienta, powinieneś ustawić znaczniki http-equiv:
// zablokowanie buforowania po stronie klienta $this->headMeta()->appendHttpEquiv('expires', 'Wed, 26 Feb 1997 08:21:57 GMT') ->appendHttpEquiv('pragma', 'no-cache') ->appendHttpEquiv('Cache-Control', 'no-cache');
Innym popularnym przykładem użycia znaczników meta jest ustawienie typu zawartości, zestawu znaków oraz języka:
// ustawienie typu zawartości i zestawu znaków $this->headMeta()->appendHttpEquiv('Content-Type', 'text/html; charset=UTF-8') ->appendHttpEquiv('Content-Language', 'en-US');
Ostatnim przykład pokazuje jak można w łatwy sposób wyświetlić komunikat bezpośrednio przez przekierowaniem używając znacznika "meta refresh":
// ustawienie czasu odświeżenia strony na 3 sekundy z nowym adresem URL: $this->headMeta()->appendHttpEquiv('Refresh', '3;URL=http://www.some.org/some.html');
Jeśli jesteś gotowy na wyświetlenie znaczników meta w layoucie, po prostu wyświetl helper:
<?= $this->headMeta() ?>
The HTML <script> element is used to either
provide inline client-side scripting elements or link to a remote resource
containing client-side scripting code. The HeadScript
helper allows you to manage both.
The HeadScript
helper supports the following methods for
setting and adding scripts:
-
appendFile($src, $type = 'text/javascript', $attrs = array())
-
offsetSetFile($index, $src, $type = 'text/javascript', $attrs = array())
-
prependFile($src, $type = 'text/javascript', $attrs = array())
-
setFile($src, $type = 'text/javascript', $attrs = array())
-
appendScript($script, $type = 'text/javascript', $attrs = array())
-
offsetSetScript($index, $script, $type = 'text/javascript', $attrs = array())
-
prependScript($script, $type = 'text/javascript', $attrs = array())
-
setScript($script, $type = 'text/javascript', $attrs = array())
In the case of the *File()
methods, $src
is
the remote location of the script to load; this is usually in the form
of a URL or a path. For the *Script()
methods,
$script
is the client-side scripting directives you wish to
use in the element.
Setting Conditional Comments
HeadScript
allows you to wrap the script tag in conditional
comments, which allows you to hide it from specific browsers. To add the conditional
tags, pass the conditional value as part of the $attrs
parameter in
the method calls.
Przykład 942. Headscript With Conditional Comments
// adding scripts $this->headScript()->appendFile( '/js/prototype.js', 'text/javascript', array('conditional' => 'lt IE 7') );
Preventing HTML style comments or CDATA wrapping of scripts
By default HeadScript
will wrap scripts with HTML
comments or it wraps scripts with XHTML cdata. This behavior can be
problematic when you intend to use the script tag in an alternative way by
setting the type to something other then 'text/javascript'. To prevent such
escaping, pass an noescape
with a value of true as part of
the $attrs
parameter in the method calls.
Przykład 943. Create an jQuery template with the headScript
// jquery template $template = '<div class="book">{{:title}}</div>'; $this->headScript()->appendScript( $template, 'text/x-jquery-tmpl', array('id='tmpl-book', 'noescape' => true) );
HeadScript
also allows capturing scripts; this can be
useful if you want to create the client-side script programmatically,
and then place it elsewhere. The usage for this will be showed in an
example below.
Finally, you can also use the headScript()
method to
quickly add script elements; the signature for this is
headScript($mode = 'FILE', $spec, $placement = 'APPEND')
.
The $mode
is either 'FILE' or 'SCRIPT', depending on if
you're linking a script or defining one. $spec
is either
the script file to link or the script source itself.
$placement
should be either 'APPEND', 'PREPEND', or 'SET'.
HeadScript
overrides each of append()
,
offsetSet()
, prepend()
, and
set()
to enforce usage of the special methods as listed above.
Internally, it stores each item as a stdClass token, which it later
serializes using the itemToString()
method. This allows you
to perform checks on the items in the stack, and optionally modify these
items by simply modifying the object returned.
The HeadScript
helper is a concrete implementation of the
Placeholder helper.
Use InlineScript for HTML Body Scripts
HeadScript
's sibling helper, InlineScript,
should be used when you wish to include scripts inline in the HTML
body. Placing scripts at the end of your document is a
good practice for speeding up delivery of your page, particularly
when using 3rd party analytics scripts.
Arbitrary Attributes are Disabled by Default
By default, HeadScript
only will render
<script> attributes that are blessed by the W3C.
These include 'type', 'charset', 'defer', 'language', and 'src'.
However, some javascript frameworks, notably Dojo, utilize custom
attributes in order to modify behavior. To allow such attributes,
you can enable them via the
setAllowArbitraryAttributes()
method:
$this->headScript()->setAllowArbitraryAttributes(true);
Przykład 944. HeadScript Helper Basic Usage
You may specify a new script tag at any time. As noted above, these may be links to outside resource files or scripts themselves.
// adding scripts $this->headScript()->appendFile('/js/prototype.js') ->appendScript($onloadScript);
Order is often important with client-side scripting; you may need to ensure that libraries are loaded in a specific order due to dependencies each have; use the various append, prepend, and offsetSet directives to aid in this task:
// Putting scripts in order // place at a particular offset to ensure loaded last $this->headScript()->offsetSetFile(100, '/js/myfuncs.js'); // use scriptaculous effects (append uses next index, 101) $this->headScript()->appendFile('/js/scriptaculous.js'); // but always have base prototype script load first: $this->headScript()->prependFile('/js/prototype.js');
When you're finally ready to output all scripts in your layout script, simply echo the helper:
<?php echo $this->headScript() ?>
Przykład 945. Capturing Scripts Using the HeadScript Helper
Sometimes you need to generate client-side scripts programmatically.
While you could use string concatenation, heredocs, and the like,
often it's easier just to do so by creating the script and
sprinkling in PHP tags. HeadScript
lets you do
just that, capturing it to the stack:
<?php $this->headScript()->captureStart() ?> var action = '<?php echo $this->baseUrl ?>'; $('foo_form').action = action; <?php $this->headScript()->captureEnd() ?>
The following assumptions are made:
-
The script will be appended to the stack. If you wish for it to replace the stack or be added to the top, you will need to pass 'SET' or 'PREPEND', respectively, as the first argument to
captureStart()
. -
The script MIME type is assumed to be 'text/javascript'; if you wish to specify a different type, you will need to pass it as the second argument to
captureStart()
. -
If you wish to specify any additional attributes for the <script> tag, pass them in an array as the third argument to
captureStart()
.
The HTML <style> element is used to include CSS stylesheets inline in the HTML <head> element.
Use HeadLink to link CSS files
HeadLink
should be used to create <link> elements for
including external stylesheets. HeadStyle
is used when
you wish to define your stylesheets inline.
The HeadStyle
helper supports the following methods for
setting and adding stylesheet declarations:
-
appendStyle($content, $attributes = array())
-
offsetSetStyle($index, $content, $attributes = array())
-
prependStyle($content, $attributes = array())
-
setStyle($content, $attributes = array())
In all cases, $content
is the actual CSS declarations.
$attributes
are any additional attributes you wish to provide to the
style tag: lang, title, media, or dir are all permissible.
Setting Conditional Comments
HeadStyle
allows you to wrap the style tag in conditional
comments, which allows you to hide it from specific browsers. To add the conditional
tags, pass the conditional value as part of the $attributes
parameter
in the method calls.
Przykład 946. Headstyle With Conditional Comments
// adding scripts $this->headStyle()->appendStyle($styles, array('conditional' => 'lt IE 7'));
HeadStyle
also allows capturing style declarations; this
can be useful if you want to create the declarations programmatically,
and then place them elsewhere. The usage for this will be showed in an
example below.
Finally, you can also use the headStyle()
method to
quickly add declarations elements; the signature for this is
headStyle($content$placement = 'APPEND', $attributes = array())
.
$placement
should be either 'APPEND', 'PREPEND', or 'SET'.
HeadStyle
overrides each of append()
,
offsetSet()
, prepend()
, and
set()
to enforce usage of the special methods as listed above.
Internally, it stores each item as a stdClass token, which it later
serializes using the itemToString()
method. This allows you
to perform checks on the items in the stack, and optionally modify these
items by simply modifying the object returned.
The HeadStyle
helper is a concrete implementation of the
Placeholder
helper.
UTF-8 encoding used by default
By default, Zend Framework uses UTF-8 as its default encoding, and,
specific to this case, Zend_View
does as well. Character encoding
can be set differently on the view object itself using the
setEncoding()
method (or the encoding
instantiation parameter). However, since Zend_View_Interface
does
not define accessors for encoding, it's possible that if you are using a custom view
implementation with this view helper, you will not have a
getEncoding()
method, which is what the view helper uses
internally for determining the character set in which to encode.
If you do not want to utilize UTF-8 in such a situation, you will
need to implement a getEncoding()
method in your custom view
implementation.
Przykład 947. HeadStyle Helper Basic Usage
You may specify a new style tag at any time:
// adding styles $this->headStyle()->appendStyle($styles);
Order is very important with CSS; you may need to ensure that declarations are loaded in a specific order due to the order of the cascade; use the various append, prepend, and offsetSet directives to aid in this task:
// Putting styles in order // place at a particular offset: $this->headStyle()->offsetSetStyle(100, $customStyles); // place at end: $this->headStyle()->appendStyle($finalStyles); // place at beginning $this->headStyle()->prependStyle($firstStyles);
When you're finally ready to output all style declarations in your layout script, simply echo the helper:
<?php echo $this->headStyle() ?>
Przykład 948. Capturing Style Declarations Using the HeadStyle Helper
Sometimes you need to generate CSS style declarations
programmatically. While you could use string concatenation,
heredocs, and the like, often it's easier just to do so by creating
the styles and sprinkling in PHP tags.
HeadStyle
lets you do just that, capturing it to the stack:
<?php $this->headStyle()->captureStart() ?> body { background-color: <?php echo $this->bgColor ?>; } <?php $this->headStyle()->captureEnd() ?>
The following assumptions are made:
-
The style declarations will be appended to the stack. If you wish for them to replace the stack or be added to the top, you will need to pass 'SET' or 'PREPEND', respectively, as the first argument to
captureStart()
. -
If you wish to specify any additional attributes for the <style> tag, pass them in an array as the second argument to
captureStart()
.
Element HTML <title>
jest używany w celu ustawienia
tytułu dla dokumentu HTML. Helper HeadTitle
pozwala na
ustawianie tytułu i przechowywanie go w celu póżniejszego pobrania
i wyświetlenia.
Helper HeadTitle
jest implementacją
helpera
Placeholder. Nadpisuje metodę toString()
aby
wygenerować element <title>
, a także dodaje metodę
headTitle()
do szybkiego i łatwego ustawiania elementów
tytułu. Sygnaturą tej metody jest
headTitle($title, $setType = 'APPEND')
; domyślnie wartość
jest dołączana na koniec stosu, ale możesz także określić opcję 'PREPEND'
(umieszczenie na początku stosu) lub 'SET' (zastąpienie stosu).
Przykład 949. Podstawowe użycie helpera HeadTitle
Możesz określić tytuł w dowolnym momencie. Najczęściej będzie tak, że ustawisz segmenty dla poszczególnych części aplikacji: strony, kontrolera, akcji i prawdopodobnie zasobu.
// ustawienie nazwy kontrolera oraz akcji jako segmentów tytułu: $request = Zend_Controller_Front::getInstance()->getRequest(); $this->headTitle($request->getActionName()) ->headTitle($request->getControllerName()); // ustawienie nazwy strony w tytule; najczęściej skryptu layoutu: $this->headTitle('Zend Framework'); // ustawienie odgranicznika dla segmentów $this->headTitle()->setSeparator(' / ');
Kiedy jesteś juz gotowy aby wyświetlić tytuł, możesz to zrobić w swoim pliku layoutu:
<!-- wyświetla <action> / <controller> / Zend Framework --> <?= $this->headTitle() ?>
Element HTML <object>
używany jest do
wstawiania do kodu strony takich elementów interaktywnych jak Flash czy
QuickTime. Helpery te pozwalają na łatwe wstawianie tych obiektów.
Obecnie dostępne są cztery helpery Object:
-
formFlash
Generuje kod do wstawiania plików Flash. -
formObject
Generuje kod do wstawiania własnego obiektu -
formPage
Generuje kod do wstawiania innych stron (X)HTML. -
formQuicktime
Generuje kod do wstawiania plików QuickTime.
Wszystkie te helpery mają podobny interfejs. Z tego powodu w dokumentacji pokażemy przykłady tylko dwóch z nich.
Przykład 950. Helper Flash
Dołączanie plików Flash do twojej strony jest bardzo łatwe. Jedynym wymaganym argumentem jest adres URI pliku.
<?php echo $this->htmlFlash('/path/to/flash.swf'); ?>
Wyświetli to następujący kod HTML:
<object data="/path/to/flash.swf" type="application/x-shockwave-flash" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"> </object>
Dodatkowo możesz określić atrybuty, parametry i zawartość jaka ma być
zrenderowana wraz z obiektem <object>
. Zostanie
do zademonstrowane za pomocą helpera htmlObject
.
Przykład 951. Konfigurowanie obiektu poprzez przekazanie dodatkowych argumentów
Pierwszy argument w helperze jest zawsze wymagany. Określa on adres
URL zasobu, który chcesz dołączyć do dokumentu (X)HTML. Drugi
argument jest wymagany tylko w helperze htmlObject
.
Inne helpery posiadają poprawną domyślną wartość dla tego argumentu.
Trzeci argument jest używany do przekazywania atrybutów do obiektu
elementu. Akceptuje on tablicę par klucz-wartość. Przykładem
mogą być atrybuty classid
oraz codebase
.
Czwarty argument przyjmuje także tylko tablice elementów w postaci
klucz-wartość i używa ich do elementów <param>
.
Ostatni argument umożliwia przekazanie dodatkowej zawartości do obiektu.
Zobacz przykład używający wszystkich argumentów.
echo $this->htmlObject( '/path/to/file.ext', 'mime/type', array( 'attr1' => 'aval1', 'attr2' => 'aval2' ), array( 'param1' => 'pval1', 'param2' => 'pval2' ), 'some content' ); /* Spowoduje to wyświetlenie: <object data="/path/to/file.ext" type="mime/type" attr1="aval1" attr2="aval2"> <param name="param1" value="pval1" /> <param name="param2" value="pval2" /> some content </object> */
Znacznik HTML <script>
używany jest zarówno do
wstawiania kodu skryptów wykonujących się po stronie klienta do treści
dokumentu jak i do załączania zewnętrznych plików zawierających taki
skrypty. Helper InlineScript
pozwala ci na obsłużenie obu
sposobów. Wywodzi się on z helpera HeadScript
więc dostępne są wszystkie jego metody; z tą różnicą, że tu używaj metody
inlineScript()
zamiast metody headScript()
.
Używaj helpera InlineScript dla skryptów w sekcji HTML Body
Helpera InlineScript
powinieneś użyć gdy chcesz dołączyć
skrypty wewnątrz sekcji HTML body
. Umieszczanie
skryptów na końcu dokumentu jest dobrą praktyką powodującą
przyspieszenie ładowania strony, szczególnie gdy używasz skryptów
statystyk pochodzących od zewnętrznych firm.
Niektóre biblioteki JS muszą być dołączone w sekcji HTML head
;
użyj helpera HeadScript
dla tych skryptów.
Przy tworzeniu widoków które zwracają obiekt JSON trzeba ustawić odpowiedni nagłówek. Tym właśnie się zajmuje helper JSON, a dodatkowo domyślnie wyłącza layouty (jeżeli są aktywne).
Helper JSON ustawia następujący nagłówek
Content-Type: application/json
Większość bibliotek Ajaxowych szuka tego nagłowka podczas parsowania odpowiedzi aby ustalić jak obsłużyć zawartość.
Użycie helpera jest następujące:
<?= $this->json($this->data) ?>
Often web sites are available in several languages. To translate the
content of a site you should simply use Zend_Translate and to
integrate Zend_Translate
within your view you should use
the Translate View Helper.
In all following examples we are using the simple Array Translation
Adapter. Of course you can also use any instance of
Zend_Translate
and also any subclasses of
Zend_Translate_Adapter
. There are several ways to initiate
the Translate View Helper:
-
Registered, through a previously registered instance in
Zend_Registry
-
Afterwards, through the fluent interface
-
Directly, through initiating the class
A registered instance of Zend_Translate
is the preferred
usage for this helper. You can also select the locale to be used simply
before you add the adapter to the registry.
Uwaga
We are speaking of locales instead of languages because a language also may contain a region. For example English is spoken in different dialects. There may be a translation for British and one for American English. Therefore, we say "locale" instead of "language."
Przykład 952. Registered instance
To use a registered instance just create an instance of
Zend_Translate
or Zend_Translate_Adapter
and register it within Zend_Registry
using
Zend_Translate
as its key.
// our example adapter $adapter = new Zend_Translate( array( 'adapter' => 'array', 'content' => array('simple' => 'einfach'), 'locale' => 'de' ) ); Zend_Registry::set('Zend_Translate', $adapter); // within your view echo $this->translate('simple'); // this returns 'einfach'
If you are more familiar with the fluent interface, then you can also create an instance within your view and initiate the helper afterwards.
Przykład 953. Within the view
To use the fluent interface, create an instance of
Zend_Translate
or Zend_Translate_Adapter
,
call the helper without a parameter, and call the
setTranslator()
method.
// within your view $adapter = new Zend_Translate( array( 'adapter' => 'array', 'content' => array('simple' => 'einfach'), 'locale' => 'de' ) ); $this->translate()->setTranslator($adapter)->translate('simple'); // this returns 'einfach'
If you are using the helper without Zend_View
then you can
also use it directly.
Przykład 954. Direct usage
// our example adapter $adapter = new Zend_Translate( array( 'adapter' => 'array', 'content' => array('simple' => 'einfach'), 'locale' => 'de' ) ); // initiate the adapter $translate = new Zend_View_Helper_Translate($adapter); print $translate->translate('simple'); // this returns 'einfach'
You would use this way if you are not working with
Zend_View
and need to create translated output.
As already seen, the translate()
method is used to return
the translation. Just call it with the needed messageid of your
translation adapter. But it can also replace parameters within the
translation string. Therefore, it accepts variable parameters in two ways:
either as a list of parameters, or as an array of parameters. As examples:
Przykład 955. Single parameter
To use a single parameter just add it to the method.
// within your view $date = "Monday"; $this->translate("Today is %1\$s", $date); // could return 'Heute ist Monday'
Uwaga
Keep in mind that if you are using parameters which are also text, you may also need to translate these parameters.
Przykład 956. List of parameters
Or use a list of parameters and add it to the method.
// within your view $date = "Monday"; $month = "April"; $time = "11:20:55"; $this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date, $month, $time); // Could return 'Heute ist Monday in April. Aktuelle Zeit: 11:20:55'
Przykład 957. Array of parameters
Or use an array of parameters and add it to the method.
// within your view $date = array("Monday", "April", "11:20:55"); $this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date); // Could return 'Heute ist Monday in April. Aktuelle Zeit: 11:20:55'
Sometimes it is necessary to change the locale of the translation. This can be done either dynamically per translation or statically for all following translations. And you can use it with both a parameter list and an array of parameters. In both cases the locale must be given as the last single parameter.
Przykład 958. Change locale dynamically
// within your view $date = array("Monday", "April", "11:20:55"); $this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date, 'it');
This example returns the Italian translation for the messageid. But it will only be used once. The next translation will use the locale from the adapter. Normally you will set the desired locale within the translation adapter before you add it to the registry. But you can also set the locale from within the helper:
Przykład 959. Change locale statically
// within your view $date = array("Monday", "April", "11:20:55"); $this->translate()->setLocale('it'); $this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date);
The above example sets 'it' as the new default locale which will be used for all further translations.
Of course there is also a getLocale()
method to get the
currently set locale.
Przykład 960. Get the currently set locale
// within your view $date = array("Monday", "April", "11:20:55"); // returns 'de' as set default locale from our above examples $this->translate()->getLocale(); $this->translate()->setLocale('it'); $this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date); // returns 'it' as new set default locale $this->translate()->getLocale();
Tak jak ze skryptami widoków, kontroler może określić stos ścieżek,
w których Zend_View
ma szukać klas helperów.
Domyślnie Zend_View
szuka klas helperów w katalogu
"Zend/View/Helper/*". Możesz wybrać inny katalog używając metod
setHelperPath()
oraz addHelperPath()
.
Dodatkowo możesz określić przedrostek klas helperów znajdujących
się w podanej ścieżce aby utworzyć przestrzenie nazw dla klas
helperów. Domyślnie, gdy żaden przedrostek nie zostanie określony,
przyjęty zostanie przedrostek 'Zend_View_Helper_'.
$view = new Zend_View(); // Ustaw ścieżkę na /path/to/more/helpers, z przedrostkiem 'My_View_Helper' $view->setHelperPath('/path/to/more/helpers', 'My_View_Helper');
Oczywiście możesz dodawać ścieżki na stos używając metody
addHelperPath()
. Gdy dodajesz ścieżki na stos,
Zend_View
będzie szukać klasy helpera począwszy od
ostatnio dodanej ścieżki. To pozwala na dodanie (lub nawet
nadpisanie) podstawowego pakietu klas helperów swoimi własnymi
klasami.
$view = new Zend_View(); // Dodaj ścieżkę /path/to/some/helpers z przedrostkiem // klasy 'My_View_Helper' $view->addHelperPath('/path/to/some/helpers', 'My_View_Helper'); // Dodaj ścieżkę /other/path/to/helpers z przedrostkiem // klasy 'Your_View_Helper' $view->addHelperPath('/other/path/to/helpers', 'Your_View_Helper'); // teraz kiedy wywołasz $this->helperName(), Zend_View będzie // wpierw szukał w "/path/to/some/helpers/HelperName" używając // nazwy klasy "Your_View_Helper_HelperName", // następnie w "/other/path/to/helpers/HelperName.php" używając // nazwy klasy "My_View_Helper_HelperName" // i ostatecznie w "Zend/View/Helper/HelperName.php" używając // nazwy klasy "Zend_View_Helper_HelperName".
Pisanie własnych klas helperów jest łatwe; po prostu pisz według poniższych zasad:
Minimalna nazwa klasy musi kończyć się nazwą helpera przy użyciu MixedCaps. Przykładowo, jeśli piszesz klasę helpera zwaną "twojHelper", minimalną nazwą klasy musi być "TwojHelper". Możesz, a nawet powinieneś nadać nazwie klasy przedrostek i jest zalecane, abyś użył 'View_Helper' jako części przedrostka: "My_View_Helper_TwojHelper". (Przedrostek będziesz musiał przekazać wraz z końcowym znakiem podkreślenia lub bez niego, do metod
addHelperPath()
orazsetHelperPath()
).Nazwa klasy musi przynajmniej składać się z nazwy helpera, używając formy MixedCaps. Np. jeśli tworzysz helper nazwany "twojHelper", nazwą klasy musi być przynajmniej "TwojHelper". Możesz, a nawet powinieneś dać nazwie klasy przedrostek i jest zalecane aby znalazła się w nim część 'View_Helper' aby cała nazwa klasy wyglądała mniej więcej tak: "My_View_Helper_TwojHelper". (Będziesz musiał przekazać ten przedrostek, ze końcowym znakiem podkreślenia lub bez, do jednej z metod
addHelperPath()
lubsetHelperPath()
).Klasa musi posiadać publiczną metodę która jest taka jak nazwa helpera; jest to metoda która zostanie wywołana gdy skrypt widoku wywoła "$this->twojHelper()". W przykładzie helpera "twojHelper", wymaganą deklaracją metody powinno być "public function twojHelper()".
Klasa nie powinna wyświetlać ani w inny sposób generować danych wyjściowych. Zamiast tego powinna zwrócić dane do wyświetlenia. Zwracane wartości powinny być odpowiednio przefiltrowane.
Klasa musi znajdować się w pliku odpowiednio do nazwy metody helpera. Przykładowo dla helpera o nazwie "twojHelper", plik powinien nazywać się "TwojHelper.php".
Umieść plik klasy helpera w katalogu który był dodany do stosu
ścieżek, a Zend_View
automatycznie załaduje klasę,
utworzy instancję, i uruchomi metodę.
Poniżej przykład kodu naszego przykładowego helpera
twojHelper
:
class My_View_Helper_TwojHelper extends Zend_View_Helper_Abstract { protected $_count = 0; public function twojHelper() { $this->_count++; $output = "I have seen 'The Jerk' {$this->_count} time(s)."; return htmlspecialchars($output); } }
Teraz w skrypcie widoku możesz wywołać helpera
TwojHelper
tyle razy ile zechcesz; instancja zostanie
utworzona raz i będzie ona istniała przez cały okres istnienia
instancji Zend_View
.
// pamiętaj, że w skrypcie widoku $this odnosi się do instancji Zend_View. echo $this->twojHelper(); echo $this->twojHelper(); echo $this->twojHelper();
Dane wyjściowe wyglądałyby w ten sposób:
I have seen 'The Jerk' 1 time(s). I have seen 'The Jerk' 2 time(s). I have seen 'The Jerk' 3 time(s).
Czasem możesz potrzebować uzyskać dostęp do obiektu
Zend_View
-- na przykład, jeśli potrzebujesz użyć
zarejestrowanego kodowania, lub chcesz renderować inny skrypt
widoku jako część klasy helpera. Aby uzyskać dostęp do obiektu
widoku, klasa helpera powinna posiadać metodę
setView($view)
, tak jak poniżej:
class My_View_Helper_ScriptPath { public $view; public function setView(Zend_View_Interface $view) { $this->view = $view; } public function scriptPath($script) { return $this->view->getScriptPath($script); } }
Jeśli twoja klasa helpera posiada metodę setView()
,
będzie ona wywołana wtedy, gdy po raz pierwszy zostanie utworzona
instancja klasy helpera i przekazany zostanie obecny obiekt
widoku. Jest to po to, aby przechować obiekt widoku w klasie helpera,
a także po to, aby określić w jaki sposób powinno się uzyskiwać do
tego obiektu dostęp.
Jeśli rozszerzasz klasę Zend_View_Helper_Abstract
nie musisz definiować tej metody, ponieważ jest ona zdefiniowana
przez klasę rozszerzaną.