MVC system in Zend Framework 2

mardi 22 janvier 2013

Most recently released Zend Framework 2. However, it complicates the study of many Russian documentation and lack of a single community. Also during the second branch of this framework, a host of innovations and buns, about which ordinary PHP programmer had not even heard of. But they can learn does not sweat. But to understand how ZF2 without understanding the logic of its MVC systems are quite difficult. Therefore, I decided to do the translation from the official site of this particular razdela.I so proceed.

MVC in Zend Framework 2



Zend \ Mvc is made of a new implementation of MVC for Zend Framework 2. The main attention was paid to the performance and flexibility.

MVC layer is based on the following components:

  1. Zend \ ServiceManager - Zend Framework provides a set of different services defined in the Zend \ Mvc \ Service. ServiceManager creates and configures an instance of your application and workflow.
  2. Zend \ EventManager - MVC is an event. This component is used everywhere. To boot the application return a response (response) and requests (request), set up and access routes (routes), as well as to process (render) view scripts (views).
  3. Zend \ Http - special object requests (request) and responses (response). Used with Zend \ Stdlib \ DispatchableInterface. All controllers are objects «dispatch».

In the MVC layer, the following auxiliaries:

  1. Zend \ Mvc \ Router - contains classes that provide routing requests. In other words, forwards the request to the desired controller.
  2. Zend \ Http \ PhpEnvironment - provides a set decorator objects HTTP requests and responses, providing an injection of queries in the current environment (including GET and POST parameters, HTTP headers).
  3. Zend \ Mvc \ Controller - set of abstract classes of controllers with basic functions, such as creating events, scheduling activities, etc.
  4. Zend \ Mvc \ Service - set ServiceManager factories and default definitions for the various application processes.
  5. Zend \ Mvc \ View - provides standard visualization scripts, desk assistants, and more. Also offers a variety of students who "bind" workflow MVC, providing features such as automatic name resolution templates, automatic model of the form and injections, etc.


The starting point is the object of the MVC Zend \ Mvc \ Application (on application). Primary responsibility is to boot resources, the direction (routing) requests to send and receive controllers, appropriate routing.

The basic structure of the application

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 receives an array application settings, located in config / application.config.php. After the application starts (Application) by calling run (), which processes the request and sends the result to the result back to the user.

Directory settings «config» contains the necessary settings used in ZendModuleManager to load modules and combining configurations (settings to connect to the database menu, ACL, etc.). For more details about what was said later.

Subdirectory «vendor» contains any third-power (auxiliary, third-party) modules of the library are necessary to ensure the performance of your application. For example, there can be placed directly the Zend Framework 2, custom libraries, or other auxiliary libraries of various projects. Libraries and modules that are located in the subdirectory «vendor» should not be altered in any way, should not be different from the original, and above them can not perform any actions of third-party applications or programs.

Directory «module» contains one or more modules to the main functionality of your application.

The basic structure of the module


Contents of the module can be absolutely anything: PHP code, functional MVC framework code-libraries, scripts, forms, public (public) resources, such as images, cascading style sheets, CSS, JavaScript code, etc. The only requirement, and that it is not required - module should act namespace (namespace) and contain a class Module.php within this namespace. This class is required for normal operation of Zend \ ModuleManager and various other tasks.

It is recommended to follow the following structure for the creation of the module:

 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 performs namespace root module is the namespace. The namespace prefix can include vendor supplies. For clarity, the module provides the basic functionality for the user «User», developed by a team may be called Zend (preferably, but not necessarily) «ZendUser» - this is also the name of the root of the namespace of the module and at the same time. File Module.php, located just to the root directory of the module will already be in the namespace of the module. See the example below:

 namespace ZendUser; class Module { } 


If you define a method init (), then it will be called the listener Zend \ ModuleManager'a, after loading the class and passing an instance of the default manager. This approach allows you to create special event listeners. BUT! Be careful with the method init ()! He called for each module on each request and should be used for the "light-weight" tasks, such as registering listeners.

The same goes for the method onBootstrap (), which takes an instance of an object MvcEvent and called for each module for each request.

Three files autoload_ *. Php optional, but desirable. They provide the following:
  • autoload_classmap.php
    Returns an array of class-map containing a pair of class name / file name. Class names are defined using magic constant __ DIR__).
  • autoload_function.php
    Returns a callback function, which can be transferred to spl_autoload_register (). Typically, the callback function uses a card that is returned to autoload_classmap.php.
  • autoload_register.php
    Registers a callback function. Typically it is in autoload_function.php.


These three files provide the default boot classes in the module without using Zend \ ModuleManager. For example, for use of the module is ZF2.

Directory «config» must contain different specific module configuration. These options can be in any format that supports Zend \ Config. It is advisable to use for the main configuration file name «module.format». For example, for the configuration file in the format name of the main PHP configuration file should be such: module.config.php. Typically you will have to create configuration files for routing and dependency injection.

Directory «src» must be compatible with the format of PSR-0 and contain the main code module. At a minimum, there must be a subdirectory named the same as the namespace of the module (the root of the module.) However, it can also contain code with different namespaces, if necessary.

Directory «test» to keep your unit-tests. Usually they are written using PHPUnit and include files related to its setting.

Directory «public» is used for shared resources. These can be pictures, CSS, JavaScript, and others completely at the discretion of the developer.

Directory «view» contains scripts species associated with different controllers.

Bootstrapping Application



Application has six main dependencies:
  1. Configuration - usually an array or object Traversable
  2. ServiceManager instance
  3. An instance of EventManager, which by default is "born" from the ServiceManager, specifying a service name «EventManager»
  4. Instance ModuleManager, which by default is "born" from the ServiceManager, specifying a service name «ModuleManager»
  5. An instance of Request, which is by default "born" from the ServiceManager, specifying a service name «Request»
  6. An instance of Response, which by default is "born" from the ServiceManager, specifying a service name «Response»


The above can be done with the initialization:

 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 has been described above, you have a choice of two things.

First, you can start downloading the application (bootstrap). The default implementation looks like this:
  • Student joins the default routing: Zend \ Mv \ cRouteListener
  • Joins the default listener to dispatch: Zend \ Mvc \ DispatchListener
  • Joins listener ViewManager: Zend \ Mvc \ View \ ViewManager
  • Event triggered the boot.

If you do not need to perform these steps, you can ask yourself alternative, extending the class of the Application and / or write the necessary code.

Second: Just run the application by calling the run (). This method does the following:
  • trigger event «route»
  • trigger event «dispatch»
  • and depending on the implementation of the previous two, possibly triggered event «render»
  • After the above, work event «finish» and return a copy of the answer.


If any errors occur during the execution of the event «route» or «dispatch», a work event «dispatch.error».

For a start it seems that there are too many to remember information that would run the application, so we do not present all available services. To start would be sufficient to use ServiceManager.

 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 your hands are very flexible with lots of different settings. Using ServiceManager you get control over the other services available, their initialization and dependency injection. Using the EventManager get 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 their processes in the application, if necessary.

Boot a modular application


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

The answer to these questions is the Zend \ ModuleManager \ ModuleManager. At first, this feature allows you to specify where the modules. He then finds each module and initializes it. Module connects the various classes of students in ModuleManager for configuration settings, students and more. If you think this is complicated, this is a wrong assumption.

Setting Module Manager


Let us first setting Module Manager. Just tell Module Manager which modules should be loaded, and if necessary, you can even specify the settings for the students and the modules.

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


To add modules, simply add items to an array of modules.

Each class module Module must determine the method getConfig (). It should return an array or object Traversable, such as Zend \ Config \ Config.Rassmotrim an example:

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


As there are a number of methods that can be defined to perform tasks such as Startup settings, providing services from the ServiceManager, event listeners, and others download more documentation ModuleManager.

Findings


ZF2 MVC layer is incredibly flexible, makes it easy to create modules and workflows in your application by using the ServiceManager and EventManager. ModuleManager is a lightweight and simple approach to the modular design, which encourages clear separation of concerns and reuse.

0 commentaires:

Enregistrer un commentaire

 
© Copyright 2010-2011 GARMOBI All Rights Reserved.
Template Design by Herdiansyah Hamzah | Published by Borneo Templates | Powered by Blogger.com.