zf2 (zend framework 2) autoload custom libraries.

@mit $ingh. August 24, 2015 Comments

Sometime we need to define our custom code by using classes/libraries. We can choose any location for those classes/libraries but the best location is vendor folder.

Step 1: Create a folder “Lib” in vendor where we shall place our custom classes/libraries.

 

Step 2: Now the main question comes. How to access to these custom libraries i.e. how to auto-load these custom classes/libraries. The answer is getAutoloaderConfig() of Module.php of any module like below.

namespace Application;

class Module{
    

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                    'Lib' => __DIR__ . '/../../vendor/Lib'
                )
            ),
        );
    }
}

 

Step 3: Now create some services in “Lib” folder

// vendor/Lib/Service1/Custom.php

namespace Lib\Service1;

class Custom{
    
    public function demo(){
        return "Service 1 Custom Class Function Called. Execute your logic here.";
    }    
}


// vendor/Lib/Service2/Custom.php

namespace Lib\Service2;

class Custom{
    
    public function demo(){
        return "Service 2 Custom Class Function Called. Execute your logic here.";
    }    
}

 

Step 4: Now its time to use our custom services in controller or anywhere like below

namespace Appliaction\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class IndexController extends AbstractActionController{

    public function indexAction(){

        $service1 = new \Lib\Service1\Custom();
        echo $service1->demo();
        
        $service2 = new \Lib\Service2\Custom();
        echo $service2->demo();
        
        exit;
    }
}

 

  • zend-framework2
  • autoload