I'm trying to autoload some Documents from Doctrine MongoDB implementation, but I'm not sure how. According to the website, the resource autoloader takes it as given that your namespace is going to use the underscore (_) rather than the new namespaces.
As an example I want to run this line:
if(!$开发者_StackOverflowthis->dm->getRepository('Documents\User')->findOneBy(array('email'=>$userInfo['email']))){
$user = new User();
//...
without having to use require. However, right now when I try to use the resource loader in bootstrap, it tells me it can't load the php file.
The repository is Repository\User namespace and User() is in Document\User namespace.
This is my bootstrap
$resourceLoader = new Zend_Loader_Autoloader_Resource(array(
'basePath' => APPLICATION_PATH.'/models/documents/',
'namespace' => 'Documents',
));
Is there a way to do this, or am I stuck using require_once in my models?
Thanks,
-Zend Noob
You could use Matthew Weier O'Phinneys Backported ZF2 Autoloaders
Features
- PSR-0-compliant
include_path
autoloading - PSR-0-compliant per-prefix or namespace autoloading
- Classmap autoloading, including classmap generation
- Autoloader factory for loading several autoloader strategies at once
Example
protected function _initAutoloader()
{
require_once 'path/to/library/ZendX/Loader/StandardAutoloader.php';
$loader = new ZendX_Loader_StandardAutoloader(array(
'namespaces' => array(
'Repository' => APPLICATION_PATH . '/models/',
'Document' => APPLICATION_PATH . '/models/',
),
));
$loader->register(); // register with spl_autoload_register()
}
The Zend autloader isn't going to cut it for the 5.3 namespaced code.
The easiest thing to do is push Doctrine's class loader into the Zend one.
Use something like this in your Bootstrap instead of your code above. In this example, I'll assume the Document
and Repository
folders are in APPLICATION_PATH . '/models'
protected function _initAutoloader()
{
$autoloader = Zend_Loader_Autoloader::getInstance();
require_once 'Doctrine/Common/ClassLoader.php';
$documentAutoloader = new \Doctrine\Common\ClassLoader('Document', APPLICATION_PATH . '/models');
$autoloader->pushAutoloader(array($documentAutoloader, 'loadClass'), 'Document');
$repositoryAutoloader = new \Doctrine\Common\ClassLoader('Repository', APPLICATION_PATH . '/models');
$autoloader->pushAutoloader(array($repositoryAutoloader, 'loadClass'), 'Repository');
return $autoloader;
}
精彩评论