Zend Framework. Первые шаги

После установки скелетного приложения Zend Framework можно приступить к более подробному ее изучению.


English
Русский
Optionally, when using Apache, you can use the APPLICATION_ENV setting in your VirtualHost to let PHP output all its errors to the browser. This can be useful during the development of your application.

Edit index.php from the zf2-tutorial/public/ directory and change it to the following:

На этапе разработки Вы можете направить вывод всех ошибок в браузер. Для этого можно воспользоваться настройкой APPLICATION_ENV на вашем виртуальном хосте.

Отредактируйте файл index.php в каталоге zf2-tutorial/public в соответствии со следующим кодом:

Code
<?php
/**
* Display all errors when APPLICATION_ENV is development.
*/
if ($_SERVER[‘APPLICATION_ENV’] == ‘development’) {
error_reporting(E_ALL);
ini_set(«display_errors», 1);
}
/**
* This makes our life easier when dealing with paths. Everything is relative
* to the application root now.
*/
chdir(dirname(__DIR__));
// Decline static file requests back to the PHP built-in webserver
if (php_sapi_name() === ‘cli-server’ && is_file(__DIR__ . parse_url($_SERVER[‘REQUEST_URI’], PHP_URL_PATH))) {
return false;
}
// Setup autoloading
require ‘init_autoloader.php’;
// Run the application!
Zend\Mvc\Application::init(require ‘config/application.config.php’)->run();

Colored with dumpz.org

Zend Framework 2 uses a module system to organise your main application-specific code within each module. The Application module provided by the skeleton is used to provide bootstrapping, error and routing configuration to the whole application. It is usually used to provide application level controllers for, say, the home page of an application, but we are not going to use the default one provided in this tutorial as we want our album list to be the home page, which will live in our own module.
Zend Framework 2 использует модульную систему для организации специфичного для Вашего приложения кода по отдельным модулям. Модуль Application, предоставленный скелетом используется для обеспечения самонастройки, маршрутизации и обработки ошибок. Он, как правило, используется для обеспечения контроллеров уровня приложения, таких как, скажем, домашняя страница приложения, однако мы не собираемся использовать стандрартную страницу для данного руководства, и хотим сделать список альбомов как домашнюю страницу, которая будет располагаться в нашем собственном модуле.
We are going to put all our code into the Album module which will contain our controllers, models, forms and views, along with configuration. We’ll also tweak the Application module as required.
Мы собираемся разместить весь наш код в модуле Album, который будет содержать наши контроллеры, модели, формы и виды вместе с настройками. Так же по необходимости настроим модуль Application.
Let’s start with the directories required.
Начнем с необходимых дирректорий.

Setting up the Album module

Настройка модуля Album

Start by creating a directory called Album under module with the following subdirectories to hold the module’s files
Начнем с создания в каталоге module директории с именем Album а так же всех ее поддиректорий для размещения файлов модуля.
 zf2-tutorial/
     /module
         /Album
             /config
             /src
                 /Album
                     /Controller
                     /Form
                     /Model
             /view
                 /album
                     /album
As you can see the Album module has separate directories for the different types of files we will have. The PHP files that contain classes within the Album namespace live in the src/Album directory so that we can have multiple namespaces within our module should we require it. The view directory also has a sub-folder called album for our module’s view scripts.
Как Вы видите, модуль Album имеет различные директорий для разных типов файлов, которые у нас будут. PHP файлы, содержащие классы в пространстве имен Album располагаются в каталоге src/Album, итак мы можем иметь несколько пространств имен в нашем модуле, которые должны нам потребоваться.
In order to load and configure a module, Zend Framework 2 has a ModuleManager. This will look for Module.php in the root of the module directory (module/Album) and expect to find a class called Album\Module within it. That is, the classes within a given module will have the namespace of the module’s name, which is the directory name of the module.
Для того, что бы загрузить и настроить модуль Zend Framework 2 имеет ModuleManager. Он ищет в корне директории модулей Module.php (module/Album) и ожидает найти в нем класс, называемый Album\Module. То есть, классы в данном модуле будут иметь пространство имен имени модуля, который совпадает с именем дирректории модуля.
Create Module.php in the Album module: Create a file called Module.php under zf2-tutorial/module/Album:
Создайте Module.php в модуле Album: В каталоге zf2-tutorial/module/Album создайте файл с именем Module.php
Code
namespace Album;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements AutoloaderProviderInterface, ConfigProviderInterface
{
public function getAutoloaderConfig()
{
return array(
‘Zend\Loader\ClassMapAutoloader’ => array(
__DIR__ . ‘/autoload_classmap.php’,
),
‘Zend\Loader\StandardAutoloader’ => array(
‘namespaces’ => array(
__NAMESPACE__ => __DIR__ . ‘/src/’ . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . ‘/config/module.config.php’;
}
}

Colored with dumpz.org

The ModuleManager will call getAutoloaderConfig() and getConfig() automatically for us.
ModuleManager автоматически вызовет getAutoloaderConfig() и getConfig()

Autoloading files

Автозагрузка файлов

Our getAutoloaderConfig() method returns an array that is compatible with ZF2’s AutoloaderFactory. We configure it so that we add a class map file to the ClassMapAutoloader and also add this module’s namespace to the StandardAutoloader. The standard autoloader requires a namespace and the path where to find the files for that namespace. It is PSR-0 compliant and so classes map directly to files as per the PSR-0 rules.
Метод getAutoloaderConfig() возвращает массив совместимый с ZF2 AutoloaderFactory. Мы настроили ее добавив файл карты классов в ClassMapAutoloader а так же добавив пространство имен этого модуля в StandartAutoloader. Стандартный загрузчик требует пространство имен и путь, по которому можно найти файлы для этого пространства имен. Массив соответствует правилам PSR-0
As we are in development, we don’t need to load files via the classmap, so we provide an empty array for the classmap autoloader. Create a file called autoload_classmap.php under zf2-tutorial/module/Album:

Так как разрабатываем мы, то не нужно загружать файлы через classmap, т.е. мы определим пустой массив для автозагрузчика карты классов. Создайте файл с именем autoload_classmap.php в каталоге zf2-tutorial/module/Album
Code
return array();

Colored with dumpz.org

As this is an empty array, whenever the autoloader looks for a class within the Album namespace, it will fall back to the to StandardAutoloader for us.
Это пустой массив будет нам возвращен всекий раз, когда загрузчик ищет класс в пространстве имен Album

Configuration

Конфигурация

Having registered the autoloader, let’s have a quick look at the getConfig() method in Album\Module. This method simply loads the config/module.config.php file.
Имея зарегистрированный автозагрузчик, давайте просмотрем метод getConfig(). Данный метод просто загружает файл config/module.config.php
English
Русский
Create a file called module.config.php under zf2-tutorial/module/Album/config
Создайте файл с именемmodule.config.php в zf2-tutorial/module/Album/config
Code
return array(
‘controllers’ => array(
‘invokables’ => array(
‘Album\Controller\Album’ => ‘Album\Controller\AlbumController’,
),
),
‘view_manager’ => array(
‘template_path_stack’ => array(
‘album’ => __DIR__ . ‘/../view’,
),
),
);

Colored with dumpz.org

The config information is passed to the relevant components by the ServiceManager. We need two initial sections: controllers and view_manager. The controllers section provides a list of all the controllers provided by the module. We will need one controller, AlbumController, which we’ll reference as Album\Controller\Album. The controller key must be unique across all modules, so we prefix it with our module name.
Конфигурационная информация передается в соответсвующие компоненты через ServiceManager. Нам нужно две внутренние секции: controllers и view_manager. Секция controllers предоставляет список всех контоллеров представленных в модуле. Нам будет нужен один контроллер, AlbumContloller, который будет отностися к Album\Controller\Album. Ключ контроллера должен быть уникальным среди всех модулей, поэтому мы используем префикс для него в соответсвии с именем нашего модуля.
Within the view_manager section, we add our view directory to the TemplatePathStack configuration. This will allow it to find the view scripts for the Album module that are stored in our view/ directory.
В секции view_manager мы добавим директорию view для настройки TemplatePathStack. Это позволит найти скрипты view для модуля Album которые храняся в каталоге view/

Informing the application about our new module

Уведомление приложения о новом модуле

We now need to tell the ModuleManager that this new module exists. This is done in the application’s config/application.config.php file which is provided by the skeleton application. Update this file so that its modules section contains the Album module as well, so the file now looks like this:

(Changes required are highlighted using comments.)

Теперь нам необходимо уведомить ModuleManager о наличии нового модуля. Это делаетмя в файле приложения config/application.config.php который предоставляется скелетным приложением. Обновите этот файл, что бы он содержал секцию модуля Album после чего он дожен выглядеть следующим образом:

(Изменения выделены комментарием)

Code
return array(
‘modules’ => array(
‘Application’,
‘Album’, // <— Add this line
),
‘module_listener_options’ => array(
‘config_glob_paths’ => array(
‘config/autoload/{{,*.}global,{,*.}local}.php’,
),
‘module_paths’ => array(
‘./module’,
‘./vendor’,
),
),
);

Colored with dumpz.org

As you can see, we have added our Album module into the list of modules after the Application module.

We have now set up the module ready for putting our custom code into it.

Как Вы можете видеть, мы добавили наш модуль Album в список модулей после модуля Application.

Теперь у нас есть готовый для вставки кода модуль.

Метки: . Закладка Постоянная ссылка.