Tuesday 16 October 2012

Zend Framework 2 : Using Classmap Generator

Since version 5, PHP has given support that very varied in OOP. One of them by overloading feature implemented on PHP 5.1.2. This feature really helps the efficiency of the writing of the code becomes more compact (so we don't need to use require or include  to load a class).

In Zend Framework 2, there is Zend\Loader\Autoloader component for autoloading of Zend Framework and your own classes. It provides functionality through two classes: StandardAutoloader and ClassMapAutoloader. here, I would explain about classmap generator that could generate Classmap Autoloader in Zend Framework .The class map autoloader its self is a high performance autoloader. It uses class maps, which are simply associative arrays of each classname to the name of the file disk that contains that class.

The contents of classmap autoloader usually like this :
   return array(
    'ZendSkeletonModule\Module'                        => __DIR__ . '/Module.php',
    'ZendSkeletonModule\Controller\SkeletonController' => __DIR__ . '/src/ZendSkeletonModule/Controller/SkeletonController.php',
    'ZendSkeletonModuleTest\Framework\TestCase'        => __DIR__ . '/tests/ZendSkeletonModule/Framework/TestCase.php',
    'ZendSkeletonModuleTest\SampleTest'                => __DIR__ . '/tests/ZendSkeletonModule/SampleTest.php',
);
The problem basically if our class in our application are pretty much. We would be getting tired and bored to write it manually. So Zend Framework 2 provides classMap generator that already exist in the vendor\ZF2\bin folder if you download ZendSkeletonApplication.

Assume that we have a structure module directory as below:


Well, the file autoload_classmap is in our module folder. So we just have to execute file ../../vendor/ZendFramework/bin/classmap_generator.php as below :
 server@server-comp:/var/www/ZendSkeletonApplication/module/Test$ php ../../vendor/ZF2/bin/classmap_generator.php -w -l ./ \ -o ./autoload_classmap.php
PHP Warning:  Module 'pdo_pgsql' already loaded in Unknown on line 0
Creating class file map for library in '/var/www/ZendSkeletonApplication/module/Test'...
Wrote classmap file to '/var/www/ZendSkeletonApplication/module/Test/autoload_classmap.php'
server@server-comp:/var/www/ZendSkeletonApplication/module/Test$ 
then if you do it correctly, the file autoload_classmap would change become like this :
 return array(
    'Test\Module'                    => __DIR__ . '/Module.php',
    'Test\Controller\TestController' => __DIR__ . '/src/Test/Controller/TestController.php',
    'Test\Model\ContohModel'         => __DIR__ . '/src/Test/Model/ContohModel.php',
);
Done !

Reference :
  1. http://samsonasik.wordpress.com/2012/03/15/zend-framework-2-classmap-generator/
  2. http://akrabat.com/zend-framework-2/using-zendloaderautoloader/

Copyright © 2012 Clighter | Powered by Blogger