The MVC system of Zend Framework 2

Hello dear Gabriele.
Recently released Zend Framework 2. However, his study of the many complicates the lack of Russian documentation, and a unified community. As for the second branch of this framework, a host of innovations and buns, about which the usual PHP programmer had never heard of before. But they can be explored, especially not sweating. But to understand how ZF2 without understanding the logic of its MVC system quite difficult. So I decided to make a translation from the official site of this section.And so begin.

MVC in Zend Framework 2



Zend\Mvc is a brand new implementation of MVC system of Zend Framework 2. Focused on performance and flexibility.

the MVC Layer is built on the basis of the following components:

    the
  1. Zend\ServiceManager — Zend Framework provides a set of different services defined in the Zend\Mvc\Service. The ServiceManager creates and configures your application instance and workflow.
  2. the
  3. Zend\EventManager – MVC is events. This component is used everywhere. For the initial download of the application, return response (response) and requests (request), setting and retrieving routes (routes) and to process (render) the view scripts (views).
  4. the
  5. Zend\Http is a special facility requests (request) and response (response). Used with Zend\Stdlib\DispatchableInterface. All controllers are objects "dispatch".

In the MVC layer uses the following additional components:

    the
  1. Zend\Mvc\Router contains classes that provide the routing of requests. In other words, redirects the requests to appropriate controllers.
  2. the
  3. Zend\Http\PhpEnvironment provides a set of decorators of objects HTTP requests and responses, providing the injection of requests in the current environment (including GET and POST parameters, HTTP headers).
  4. the
  5. Zend\Mvc\Controller – a set of abstract controller classes with basic functionality, such as creating events, scheduling of actions, etc.
  6. the
  7. Zend\Mvc\Service – a set of ServiceManager factories and definitions of default for different processes of the application.
  8. the
  9. Zend\Mvc\View provides default visualization view scripts, registration assistants, and more. Also provides various listeners which bind the MVC workflow, providing features such as automatic name resolution templates, automatic creation of view model and injections, etc.


The starting point of the work of the MVC is an object Zend\Mvc\Application (hereinafter Application). Main responsibilities are initial loading of resources, the direction (routing) of requests, and sending and receiving controller corresponding to the routing.

basic outline

the
application_root/
config/
application.config.php
autoload/
global.php
local.php
// etc.
data/
module/
vendor/
public/
.htaccess
index.php
init_autoloader.php


For redirecting all user requests to the site meets the file public/index.php. Then gets an array of application settings, located in config/application.config.php. After launching an Application (Application) by calling the function run(), which processes the requests and eventually sends the result back to the user.

Settings directory "config" contains options used in ZendModuleManager to load modules and merge configuration (connection settings, database, menu, ACL, etc.). For more detail about discussed a little later.

The subdirectory "vendor" includes any third - power (auxiliary, third-party) modules of the library need to ensure the health of Your app. For example, there may be placed directly Zend Framework 2, custom libraries, or other support libraries for the various projects. Libraries and modules are located in the subdirectory "vendor" shall not be altered in any way, should not differ from the original, they cannot perform any actions from within the app or third-party programs.
Directory "module" contains one or more modules that provide the main functionality of Your app.

basic structure of a module


The contents of the module can be absolutely anything: PHP code, functional MVC structures, library code, scripts types, public (public) resources such as images, cascading style sheets CSS, JavaScript code and etc. the Only requirement, and it is not compulsory — the module must act as the namespace (namespace) and must contain a class Module.php within that namespace. This class is necessary for the normal operation of Zend\ModuleManager and some other tasks.

We recommend the following structure when creating a module:

the
module_root < named-after-module-namespace>/
Module.php
autoload_classmap.php
autoload_function.php
autoload_register.php
config/
module.config.php
public/
images/
css/
js/
src/
<module_namespace>/
<code files>
test/
phpunit.xml
bootstrap.php
<module_namespace>/
<test code files>
view/
<dir-named-after-module-namespace>/
<dir-named-after-a-controller>/
<.phtml files>


Due to the fact that the module acts as a namespace, the root directory of the module is the namespace. The namespace may include ventory prefix set. For clarity, the module provides the basic functionality for the user "User", developed by the Zend team can be called (preferably, but not necessarily) "ZendUser" — as it is the name of the root folder of the module and namespace at the same time. File Module.php located directly in the root folder of the module will already be in the namespace of this module. Look the example below:

the
namespace ZendUser;

class Module
{
}


If defined init () method, it will be called by the listener Zend\ModuleManager'and, after loading the class, and passing in an instance of the Manager by default. This approach allows us to create a special event listener. BUT! Be careful with the method init()! It is called for every module on every request, and shall only be used for lightweight tasks such as registering listeners.

Same goes for method onBootstrap () which accepts an MvcEvent instance of the object and is called for every module on every request.

Three files autoload_*.php is optional but desirable. They provide the following:
the
    the
  • autoload_classmap.php
    Returns a map array of classes containing the class name/file name. The class names are determined by the magic constants __DIR__).
  • the
  • autoload_function.php
    Returns a callback that can be passed to spl_autoload_register(). Typically, the callback function uses the map returned in the autoload_classmap.php.
  • the
  • autoload_register.php
    Registers a callback function. Usually it is autoload_function.php.


These three files provide a download of the default classes in a module without using a Zend\ModuleManager. For example to use modules outside of ZF2.

Directory "config" must contain specific module configuration. These settings can be in any format that supports Zend\Config. It is desirable to use for the main configuration file the name "module.format". For example, for file configuration in PHP format the name of the main configuration file should be: module.config.php. Usually You will have to create the configuration files for routing and injecting dependencies.

The "src" directory must be compatible with PSR-0 and contain the main code of the module. At least, it should be a subdirectory named the same as the module namespace (the root folder of the module). However, it can contain code and different namespaces if necessary.

The directory "test" should contain your unit tests. Usually they are written using PHPUnit, and contain files associated with configuration.

Directory "public" is used for public resources. It could be images, CSS, JavaScript etc. Completely at the discretion of the developer.
Directory "view" contains view scripts related to various controllers.

bootstrapping applications



The application has six basic dependencies:
    the
  1. Configuration, usually an array or Traversable object
  2. the
  3. an Instance of ServiceManager
  4. the
  5. an instance of the EventManager, which by default is "born" from ServiceManager, the job of the service name "EventManager"
  6. the
  7. an Instance of ModuleManager, which by default is "born" from ServiceManager, the job of the service name "ModuleManager"
  8. the
  9. an Instance of Request, which by default is "born" from ServiceManager, the job of the service name "Request"
  10. the
  11. the Response Instance, which by default is "born" from ServiceManager, the job of the service name "Response"


The above can be realized when it is initialized:

the
use Zend\EventManager\EventManager;
use Zend\Http\PhpEnvironment;
use Zend\ModuleManager\ModuleManager;
use Zend\Mvc\Application;
use Zend\ServiceManager\ServiceManager;

$config = include 'config/application.config.php';

$serviceManager = new ServiceManager();
$serviceManager- > setService('EventManager', new EventManager());
$serviceManager- > setService('ModuleManager', new ModuleManager()); 
$serviceManager- > setService('Request', new PhpEnvironmentRequest());
$serviceManager- > setService('Response', new PhpEnvironmentResponse());

$application = new Application($config, $serviceManager);


After doing all that was described above, You have the choice of two actions.

First: You can start the download of the application (bootstrap). In default implementation it looks like this:
the

    Subscribes a listener default routing: Zend\Mv\cRouteListener

    Subscribes a listener default dispatch: Zend\Mvc\DispatchListener

    Subscribes a listener ViewManager: Zend\Mvc\View\ViewManager

    the event Fires bootstrap.


If You do not need to perform these actions, you can specify alternatives, extending the Application class and/or simply by writing the necessary code.

Second: Just start the application by calling the run () method. This method will do the following:
the

    the event is triggered "route" the

  • will work event of "dispatch"
  • the
  • and depending on the implementation of the previous two, perhaps the event is triggered "render"
  • the
  • after the above, the event is triggered on "finish" and return a response instance.


If errors occur during execution of the event "route" or "dispatch" will "event dispatch.error."

For a start think you need to memorize a lot of information to run the application, so we do not present all services available. Should be enough to start using the ServiceManager.

the
use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceManager;

// setup autoloader
AutoloaderFactory::factory();

// get application stack configuration
$configuration = include 'config/application.config.php';

// setup service manager
$serviceManager = new ServiceManager(new ServiceManagerConfig());
$serviceManager- > setService('ApplicationConfig', $configuration);

// load modules -- which will provide services, configuration, and more
$serviceManager- > get('ModuleManager')->loadModules();

// bootstrap and run application
$application = $serviceManager- > get('Application');
$application- > bootstrap();
$response = $application->run();
$response->send();


Very quickly You will notice that You have in your hands a very flexible system with lots of different settings. Using the ServiceManager, You get control over the other available services, their initialization and implementation of dependences. Using the EventManager get a chance to catch any events that occur in the application ("bootstrap", "route", "dispatch", "dispatch.error", "render", "finish"), at any time and in any place that allows you to create your processes in the application if necessary.

bootstrapping a modular application


The previously described approach works. But the question arises, where did the application settings? It is logical to assume that the settings are taken directly from the module. And then to get these settings at their disposal?

The answer to these questions is a Zend\ModuleManager\ModuleManager. First, this component allows You to specify where to find the modules. Then it finds each module and initialisere it. Classes Module contact various students in ModuleManager to ensure configuration settings, listeners, and more. If You think it's complex, then it is a wrong assumption.
configuration Manager Module


Firstly, we will configure the Module Manager. Simply inform the Module Manager which modules to download, and if necessary you can even specify settings for listeners of the modules.

Now let's think about the file application.config.php described previously. Define settings as follows:
the
<?php
// config/application.config.php
return array(
'modules' => array(
/* ... */
),
'module_listener_options' => array(
'module_paths' => array(
'./module',
'./vendor',
),
),
);


To add modules, you simply add elements to an array of modules.

Each class module module needs to determine the method getConfig(). It must return array or Traversable object such as Zend\Config\Config.Consider the example:

the
namespace ZendUser;

class Module
{
public function getConfig()
{
return include __DIR__ . '/config/module.config.php'
}
}


Also, there are a number of methods that you can define to perform tasks such as startup settings, providing services from ServiceManager, event listener load, etc. in More detail in the documentation ModuleManager.

Conclusions


The ZF2 MVC layer is incredibly flexible, makes it easy to create modules and workflows in Your application using the ServiceManager and EventManager. ModuleManager is a lightweight and simple approach to modular architecture that encourages clean separation of concerns and code reuse.

Links


For more details see the documentation on Ukrainian community ZF2.
Original article
Article based on information from habrahabr.ru

Комментарии

Популярные сообщения из этого блога

The release of the new version of the module modLivestreet 0.3.0-rc

mSearch: search + filter for MODX Revolution

Emulator data from GNSS receiver NMEA