Search code examples
phpzend-frameworkautoloaddirectory-structure

class loading error after adding application/services to zend framework site


I'm trying to add a new folder to the application folder in zend framework, but none of the classes I create in the new folder can be found.

What I have is this structure:

application/
  models/
  modules/
  services/
    Test.php

I tried to call on the class Test.php:

class Service_Test{

}

$test = new Service_Test()

This results in the error: PHP Warning: include_once(): Failed opening 'Service/Test.php' for inclusion (include_path='...') in library/Zend/Loader.php on line 146.

(The include_path contains a list of directories, which I removed for privacy).

I thought that Services would be automatically found in the same way that Models are automatically found. Does anyone know how I can make Zend framework find the Services folder?


I tried this as well:

require_once('Zend/Loader.php');
Zend_Loader::registerAutoload();
    $resourceLoader = new Zend_Loader_Autoloader_Resource(array(
        'basePath'  => ROOT_PATH . '/application',
        'namespace' => 'Service',
    ));

PHP Fatal error: Class 'Service_Test' not found


Solution

  • Thanks everyone for your help. I finally figured out what was going on. The site I am working on has an atypical setup. It's not extending any Zend Framework bootstrap class, or calling Zend_Application. The way classes were being autoloaded is by using:

    set_include_path(ROOT_PATH . '/application/models'.PATH_SEPARATOR .
                 ROOT_PATH . '/library'.PATH_SEPARATOR .
             get_include_path());
    
    require_once('Zend/Loader.php');
    @Zend_Loader::registerAutoload();
    

    I changed it to:

    set_include_path(ROOT_PATH . '/application/models'.PATH_SEPARATOR .
                 ROOT_PATH . '/library'.PATH_SEPARATOR .
             get_include_path());
    
    require_once 'Zend/Loader/Autoloader.php';
    $autoloader = Zend_Loader_Autoloader::getInstance();
    $autoloader->setFallbackAutoloader(true);
    $resources = new Zend_Loader_Autoloader_Resource(array(
              'namespace' => '',
              'basePath'  => ROOT_PATH . '/application/',
          ));
    $resources->addResourceTypes(array(
              'service' => array(
                  'path'      => 'services',
                  'namespace' => 'Service',
              )));
    

    Technically, I did not have to add the resource, but if I didn't, and just relied on putting /application/services into the include path, then I would not be able to prefix my classes with 'Service_'.

    I'm not sure I would recommend this setup (no Bootstrap class extension or use of Zend_Application) for anyone else. It would be interesting to see what other people thought of this practice. Good or bad? In any case, that is how I solved the issue.