Will a directory with a period break autoload resolution based on a namespace in Zend Framework?

265 views Asked by At

I have a folder in my library folder which is named after my website. The folder path is like:

~\www\library\myWebsite.com

If I'm using Zend autoloader to load the namespace of everything in the library path, will I have any trouble autoloading a class from that file with a namespace like this:

\myWebsite.com\myClass::myFunction();

I have looked online for documentation on this and I can't find any info about using periods in this way.

2

There are 2 answers

0
Jesse Greathouse On BEST ANSWER

I tried it and the complication is in PHP. I think Zend is registering the namespace fine, because when I call \Zend_Load_Autoloader::getRegisteredNamespaces() it shows that it's registered. but when I call the static method from the fully qualified namespace, php gives an error of this:

Fatal error: Undefined constant 'myWebsite' in /home/jesse/www/application/controllers/MyController.php on line 15 

It seems like PHP is terminating the namespace identifier, during parsing, at the . (period character). This is dissapointing because to me having a library named after the website was important to my design.

I will rename the directory to myWebsitecom or possibly make the .com it's own sub directory like

myWebsite\com and incorporate that into my namespace tree like: \MyNamespace\Com\MyClass::myFunction();

0
Stephen Fuhry On

The easiest way to find out is to try it.

If it doesn't work, you could always write a custom autoloader to make it work. I don't have much experience with php namespaces, but the autoloader would look something like this (I imagine you'll have to tinker with it a bit to determine the correct file path given the class name):

<?php
class My_Loader_Autoloader_MyWebsite implements Zend_Loader_Autoloader_Interface {

    /**
     * (non-PHPdoc)
     * @see Zend_Loader_Autoloader_Interface::autoload()
     */
    public function autoload($class) {

        if (strtolower(substr($class, 0, 9)) == 'mywebsite') {
            $file = realpath(APPLICATION_PATH . '/../library/myWebsite.com/' . $class);
            if ($file) {
                require_once $file;
                return $class;
            }
        }
        return false;
    }
}

then put this in your bootstrap:

$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->pushAutoloader(new My_Loader_Autoloader_MyWebsite());

and if this class must be in that myWebsite.com directory, you could just cheat and throw in a require in there too:

 require_once(APPLICATION_PATH . '/../library/myWebsite.com/Loader/Autoloader/MyWebsite.php');