Search code examples
phpzend-frameworkzend-autoloader

define PHP class on the fly in a zend application


Within a Zend app, is there a way to define a class which does not conform to autoloading naming conventions and still have it recognized when I try to use it later on? I imagine you define the class and register it, somehow, with the autoloader, but after reading the autoloader manpage, I still don't understand how to do it.

My use case is during testing (and no, I don't want a mock or stub in this case). I define a new class at the top of my test script, but when my application code references that class, the autolader aggressively tires to load it based on naming convention.

<?php 

class Non_Conforming_Dummy_Class 
{
}

// should I register this new class with the autoloader right here? 

class Whatever
{
public function useIt()
    {
        $class = new Non_Conforming_Dummy_Class;
    }
}

I get a 'no such file or directory' which looks for Non/Conforming/Dummy/Class.php


Solution

  • The ZF Autoloader will load any classes following PSR-0 convention. Any classes not following that convention cannot be loaded with the Autoloader. However, you can

    register arbitrary autoloader callbacks, optionally with a specific namespace (or group of namespaces). Zend_Loader_Autoloader will attempt to match these first before using its internal autoloading mechanism.

    This means, you can add your own autoloader that knows your naming scheme to ZF's autoloader:

    $autoloader->pushAutoloader(array('myAutoloader', 'autoload'), 'MyPrefix');
    

    See http://framework.zend.com/manual/en/zend.loader.autoloader.html