Programmer's Reference Guide
| Введение |
Страницы
Zend_Navigation поставляется с двумя типами страниц:
-
страницы MVC, с использованием класса Zend_Navigation_Page_Mvc
-
страницы URI, с использованием класса Zend_Navigation_Page_Uri
action, controller,
module, route, params).
Страницы URI определяются единственным свойством uri,
которое дает возможность гибко ссылаться на страницы других сайтов
или производить другие действия со сгенерированными ссылками.
Общие функциональные возможности страниц
Все классы страниц должны расширять Zend_Navigation_Page, таким образом они будут наследовать один общий набор функциональных возможностей и свойств.
Для опций есть соотвествующие установочные методы с префиксом
set.
Это означает, что опции order соответствует метод
setOrder(), а опции reset_params -
метод setResetParams().
Если для опции нет соответствующего метода для установки, то она будет
устанавливаться как пользовательское свойство страницы.
Более подробную информацию о расширении Zend_Navigation_Page читайте в разделе о создании своих типов страниц.
| Ключ | Тип | Значение по умолчанию | Описание |
|---|---|---|---|
label |
String | NULL | Наименование страницы, например, "Главная" или "Блог". |
id |
String | int |
NULL | Идентификатор, который может использоваться при рендеринге данной страницы, обычно в качестве атрибута id в элементе ссылки. |
class |
String | NULL | Класс CSS, который может использоваться при рендеринге данной страницы, обычно в элементе ссылки. |
title |
String | NULL |
Краткое описание страницы, обычно оно используется
в качестве атрибута title ссылки.
|
target |
String | NULL | Задает целевой фрейм для страницы, обычно используется в качестве соответствующего атрибута ссылки. |
rel |
Array | array() |
Определяет "направленные вперед" связи
(forward relations) для страницы,
т.е. отношение текущего ресурса к тому,
на который ссылается страница.
Все элементы в массиве являются парами ключ-значение,
где ключ обозначает тип связи, а значение является
указателем на связанную страницу.
Примером такой пары ключ-значение может быть
'alternate' => 'format/plain.html'.
С целью обеспечения полной гибкости на значения из пар
ключ-значение не накладывается никаких ограничений.
Значение не обязательно должно быть строкой.
Для получения более подробной информации об опциях
rel и rev читайте
раздел
о помощнике ссылок.
|
rev |
Array | array() |
Определяет "обратные" связи (reverse relations) для
страницы,
т.е. отношение ресурса, на который ссылается данная
страница, к текущему.
Работает в точности так же, как rel.
|
order |
String | int | NULL |
NULL |
Работает так же, как одноименная опция для элементов
форм в
Zend_Form.
Страницы будут обходиться в указанном через эту опцию
порядке, это значит, что вы можете
сделать так, чтобы страница была первой в итерации,
присвоив атрибуту order какое-то наименьшее
значение, например, -100.
Если передается строка, то она должна
преобразовываться в валидный int.
В случае значения NULL
будет использоваться порядок, в котором страницы были
добавлены в контейнер.
|
resource |
String | Zend_Acl_Resource_Interface | NULL | NULL | Ресурс ACL, который требуется связать со страницей. Более подробную информацию читайте в разделе об интеграции ACL в помощники видов. |
privilege |
String | NULL | NULL | Привилегия ACL, которую требуется связать со страницей. Более подробную информацию читайте в разделе об интеграции ACL в помощники видов. |
active |
bool |
FALSE |
Должна ли страница считаться активной для
текущего запроса.
Если эта опция равна FALSE или
не передана, то страница MVC
будет сверять свои свойства с объектом запроса во
время вызова $page->isActive().
|
visible |
bool |
TRUE | Должна ли страница быть видимой для пользователя или просто быть частью структуры. Невидимые страницы пропускаются в помощниках видов. |
pages |
Array | Zend_Config | NULL | NULL | Дочерние по отношению к данной страницы. Это может быть массив или объект Zend_Config, содержащий либо опции страниц, которые могут быть переданы фабричному методу, либо сами экземпляры Zend_Navigation_Page. Массивы опций страниц и объекты Zend_Navigation_Page могут комбинироваться друг с другом. |
Замечание: Пользовательские свойства
Все страницы поддерживают установку и получение пользовательских свойств путем использования "магических" методов __set($name, $value), __get($name), __isset($name) и __unset($name). Пользовательские свойства могут иметь любые значения и будут включаться в массив, возвращаемый методом$page->toArray(). Последнее значит, что страницы могут успешно подвергаться сериализации/десериализации даже в том случае, если они содержат свойства, не определенные в классе страницы.
Как предопределенные, так и пользовательские свойства могут устанавливаться через метод$page->set($name, $value)и извлекаться через метод$page->get($name), также можно использовать "магические" методы.
Пример #1 Пользовательские свойства страницы
Данный пример показывает, как могут использоваться пользовательские свойства.
- $page = new Zend_Navigation_Page_Mvc();
- $page->foo = 'bar';
- $page->meaning = 42;
- if ($page->meaning != 42) {
- // должны быть какие-либо действия
- }
Zend_Navigation_Page_Mvc
MVC pages are defined using MVC parameters known from the Zend_Controller component. An MVC page will use Zend_Controller_Action_Helper_Url internally in the getHref() method to generate hrefs, and the isActive() method will intersect the Zend_Controller_Request_Abstract params with the page's params to determine if the page is active.
| Key | Type | Default | Description |
|---|---|---|---|
action |
String | NULL | Action name to use when generating href to the page. |
controller |
String | NULL | Controller name to use when generating href to the page. |
module |
String | NULL | Module name to use when generating href to the page. |
params |
Array | array() | User params to use when generating href to the page. |
route |
String | NULL | Route name to use when generating href to the page. |
reset_params |
bool |
TRUE | Whether user params should be reset when generating href to the page. |
Замечание: The three examples below assume a default MVC setup with the
defaultroute in place.
The URI returned is relative to thebaseUrlin Zend_Controller_Front. In the examples, the baseUrl is '/' for simplicity.
Пример #2 getHref() generates the page URI
This example shows that MVC pages use
Zend_Controller_Action_Helper_Url internally
to generate URIs when calling $page->getHref().
- // getHref() returns /
- 'action' => 'index',
- 'controller' => 'index'
- ));
- // getHref() returns /blog/post/view
- 'action' => 'view',
- 'controller' => 'post',
- 'module' => 'blog'
- ));
- // getHref() returns /blog/post/view/id/1337
- 'action' => 'view',
- 'controller' => 'post',
- 'module' => 'blog',
- ));
Пример #3 isActive() determines if page is active
This example shows that MVC pages determine whether they are active by using the params found in the request object.
- /*
- * Dispatched request:
- * - module: default
- * - controller: index
- * - action: index
- */
- 'action' => 'index',
- 'controller' => 'index'
- ));
- 'action' => 'bar',
- 'controller' => 'index'
- ));
- $page1->isActive(); // returns true
- $page2->isActive(); // returns false
- /*
- * Dispatched request:
- * - module: blog
- * - controller: post
- * - action: view
- * - id: 1337
- */
- 'action' => 'view',
- 'controller' => 'post',
- 'module' => 'blog'
- ));
- // returns true, because request has the same module, controller and action
- $page->isActive();
- /*
- * Dispatched request:
- * - module: blog
- * - controller: post
- * - action: view
- */
- 'action' => 'view',
- 'controller' => 'post',
- 'module' => 'blog',
- ));
- // returns false, because page requires the id param to be set in the request
- $page->isActive(); // returns false
Пример #4 Using routes
Routes can be used with MVC pages. If a page has a route, this route will be used in getHref() to generate the URL for the page.
Замечание: Note that when using the
routeproperty in a page, you should also specify the default params that the route defines (module, controller, action, etc.), otherwise the isActive() method will not be able to determine if the page is active. The reason for this is that there is currently no way to get the default params from a Zend_Controller_Router_Route_Interface object, nor to retrieve the current route from a Zend_Controller_Router_Interface object.
- // the following route is added to the ZF router
- Zend_Controller_Front::getInstance()->getRouter()->addRoute(
- 'article_view', // route name
- new Zend_Controller_Router_Route(
- 'a/:id',
- 'module' => 'news',
- 'controller' => 'article',
- 'action' => 'view',
- 'id' => null
- )
- )
- );
- // a page is created with a 'route' option
- 'label' => 'A news article',
- 'route' => 'article_view',
- 'module' => 'news', // required for isActive(), see note above
- 'controller' => 'article', // required for isActive(), see note above
- 'action' => 'view', // required for isActive(), see note above
- ));
- // returns: /a/42
- $page->getHref();
Zend_Navigation_Page_Uri
Pages of type Zend_Navigation_Page_Uri can be
used to link to pages on other domains or sites, or to implement
custom logic for the page. URI pages are simple; in addition
to the common page options, a URI page takes only one option —
uri. The uri will be returned when
calling $page->getHref(), and may be a
String or NULL.
Замечание: Zend_Navigation_Page_Uri will not try to determine whether it should be active when calling
$page->isActive(). It merely returns what currently is set, so to make a URI page active you have to manually call$page->setActive()or specifyingactiveas a page option when constructing.
| Key | Type | Default | Description |
|---|---|---|---|
uri |
String | NULL | URI to page. This can be any string or NULL. |
Creating custom page types
When extending Zend_Navigation_Page, there is usually no need to override the constructor or the methods setOptions() or setConfig(). The page constructor takes a single parameter, an Array or a Zend_Config object, which is passed to setOptions() or setConfig() respectively. Those methods will in turn call set() method, which will map options to native or custom properties. If the option internal_id is given, the method will first look for a method named setInternalId(), and pass the option to this method if it exists. If the method does not exist, the option will be set as a custom property of the page, and be accessible via $internalId = $page->internal_id; or $internalId = $page->get('internal_id');.
Пример #5 The most simple custom page
The only thing a custom page class needs to implement is the getHref() method.
- class My_Simple_Page extends Zend_Navigation_Page
- {
- public function getHref()
- {
- return 'something-completely-different';
- }
- }
Пример #6 A custom page with properties
When adding properties to an extended page, there is no need to override/modify setOptions() or setConfig().
- class My_Navigation_Page extends Zend_Navigation_Page
- {
- private $_foo;
- private $_fooBar;
- public function setFoo($foo)
- {
- $this->_foo = $foo;
- }
- public function getFoo()
- {
- return $this->_foo;
- }
- public function setFooBar($fooBar)
- {
- $this->_fooBar = $fooBar;
- }
- public function getFooBar()
- {
- return $this->_fooBar;
- }
- public function getHref()
- {
- return $this->foo . '/' . $this->fooBar;
- }
- }
- // can now construct using
- 'label' => 'Property names are mapped to setters',
- 'foo' => 'bar',
- 'foo_bar' => 'baz'
- ));
- // ...or
- 'type' => 'My_Navigation_Page',
- 'label' => 'Property names are mapped to setters',
- 'foo' => 'bar',
- 'foo_bar' => 'baz'
- ));
Creating pages using the page factory
All pages (also custom classes), can be created using the page
factory, Zend_Navigation_Page::factory(). The factory
can take an array with options, or a
Zend_Config object. Each key in the
array/config corresponds to a page option, as seen in the
section on Pages.
If the option uri is given and no MVC options are
given (action, controller, module, route), an URI
page will be created. If any of the MVC options are given, an
MVC page will be created.
If type is given, the factory will assume the value to
be the name of the class that should be created. If the value is
mvc or uri and MVC/URI page will be created.
Пример #7 Creating an MVC page using the page factory
- 'label' => 'My MVC page',
- 'action' => 'index'
- ));
- 'label' => 'Search blog',
- 'action' => 'index',
- 'controller' => 'search',
- 'module' => 'blog'
- ));
- 'label' => 'Home',
- 'action' => 'index',
- 'controller' => 'index',
- 'module' => 'index',
- 'route' => 'home'
- ));
- 'type' => 'mvc',
- 'label' => 'My MVC page'
- ));
Пример #8 Creating a URI page using the page factory
- 'label' => 'My URI page',
- 'uri' => 'http://www.example.com/'
- ));
- 'label' => 'Search',
- 'uri' => 'http://www.example.com/search',
- 'active' => true
- ));
- 'label' => 'My URI page',
- 'uri' => '#'
- ));
- 'type' => 'uri',
- 'label' => 'My URI page'
- ));
Пример #9 Creating a custom page type using the page factory
To create a custom page type using the factory, use the option
type to specify a class name to instantiate.
- class My_Navigation_Page extends Zend_Navigation_Page
- {
- protected $_fooBar = 'ok';
- public function setFooBar($fooBar)
- {
- $this->_fooBar = $fooBar;
- }
- }
- 'type' => 'My_Navigation_Page',
- 'label' => 'My custom page',
- 'foo_bar' => 'foo bar'
- ));
| Введение |
