Search code examples
phpmodulezend-framework2

Zf2 extending the class giving the error class not found


I am trying to create the library inside the vendor folder in ZF2. Here is the structure:

/Vendor
     /Mylib
          /Mylib.php
          /MylibStore.php
          /MylibError.php
          ....

I have declared the same lib in Applicaiotion/Module.php:

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

Now I am calling Mylib class in controller it is working but when I am trying to instantiate other class in controller it is giving the error. Here is snap of code:

Mylib.php

namespace Mylib;
abstract class Mylib
{ 

MylibStore.php

namespace MylibStore;
use \Mylib\MylibError;
class MylibStore extends MylibError
{

MylibError.php

namespace MylibError;
class MylibError
{

I am getting the following error :

Fatal error: Class 'MylibStore\MylibError' not found in C:\xampp\htdocs\coxaxle\vendor\Mylib\MylibStore.php on line 5

Please let me know what I am doing wrong? And how can I resolve this issue?


Solution

  • Problem is in your namespaces. All your files inside Mylib directory should have same namespace- Mylib.
    That's why only Mylib class works, because it has correct namespace.

    If you put your classes in separate directories then you have to update namespace about this directory.

    Example:

    /Vendor
         /Mylib
              /Service
                  /MylibService.php
              /Mylib.php
              ....
    

    Class Mylib should have namespace Mylib
    Class MylibService should have namespace Mylib\Service