How to access a custom repository from a controller in doctrine 2.0 and Zend framework?
Im unable to access a custom repository from a controller in doctrine 2.0 and Zend framework?
I have my file structure as following:-
application/controllers
/configs
/domain/
Entities/User.php
/Mappings/User.php
Proxies/
Repositories/
vendor/
Doctrine
In User.php, i have included like this:
namespace Repositories;
use Doctrine\ORM\EntityRepository;
/**
* @entity(repositoryClass="Repositories\UserRepository")
* @开发者_StackOverflow中文版Table(name="User")
*/
class User
{
}
Even i tried with
namespace Entities;
use Doctrine\ORM\EntityRepository;
/**
* @entity(repositoryClass="Entities\UserRepository")
* @Table(name="User")
*/
class User
{
}
Ive generated repositories to the domain/Repositories by the command.
Now i have my customized repositories in the folder domain/Repositories. Ill want to access the ex: UserRepository in my UserController.php I tried this.
$this->em = Zend_Registry::get('em');
$userlist = $this->em->getRepository('Repostories\User')->getusers();
Output: No such file or directory
If i tried:
$this->em->getRepository('Entities\User')->getusers();
Output: getusers() function is missing. ur function should start by findBy
Please help in regards to this.
Thanks, Hephzibah.
Start with the repository
// Repositories/UserRepository.php
namespace Repositories;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function getusers()
{
// etc
}
}
Now the entity
// Entities/User.php
namespace Entities;
/**
* @Entity(repositoryClass="Repositories\UserRepository")
*/
class User
{
// etc
}
Provided your autoloader can find classes in both Repositories
and Entities
namespaces, the following should work
$em->getRepository('Entities\User')->getusers();
I agree with Phil that this is most likely an issue of autoloading - I ran into the same problem. It was solved by adding an _init function to the application bootstrap file with entries for my service, entity, and repository classes like below. You'll have to adjust yours to match your paths, obviously. My structure has Service, Entity, and Repository directories inside the default Zend Framework models directory.
protected function _initAutoloader()
{
$autoloader = Zend_Loader_Autoloader::getInstance();
require_once 'Doctrine/Common/ClassLoader.php';
$serviceAutoloader = new \Doctrine\Common\ClassLoader('Service', APPLICATION_PATH . '/models');
$autoloader->pushAutoloader(array($serviceAutoloader, 'loadClass'), 'Service');
$entityAutoloader = new \Doctrine\Common\ClassLoader('Entity', APPLICATION_PATH . '/models');
$autoloader->pushAutoloader(array($entityAutoloader, 'loadClass'), 'Entity');
$repositoryAutoloader = new \Doctrine\Common\ClassLoader('Repository', APPLICATION_PATH . '/models');
$autoloader->pushAutoloader(array($repositoryAutoloader, 'loadClass'), 'Repository');
return $autoloader;
}
精彩评论