Zend Framework 1.11 с Doctrine 2 и пространствами имен

Я использовал Doctrine в своем проекте без явного указания пространства имен ни для одного из моих классов. Это привело к некоторым проблемам с попыткой организовать мой код в отдельные подкаталоги (по крайней мере, так казалось). Таким образом, я пытался внедрить пространства имен в свой код, но я борюсь и пробовал многочисленные решения здесь безрезультатно, мне нужно спросить.

У меня стандартная структура проекта:

application/
--models/
--services/
--controllers/
..etc

В моем Bootstrap у меня есть следующее (без пространств имен в моем коде, который отлично работает):

/**
* Initialize Doctrine
* @return Doctrine_Manager
*/
public function _initDoctrine() {
    // include and register Doctrine's class loader
    require_once('doctrine/Doctrine/Common/ClassLoader.php');

    $autoloader = \Zend_Loader_Autoloader::getInstance();

    require_once('doctrine/Doctrine/Common/ClassLoader.php');
    $commonLoader = new \Doctrine\Common\ClassLoader('Doctrine\Common', 'doctrine');
    $autoloader->pushAutoloader(array($commonLoader, 'loadClass'), 'Doctrine\Common');

    $dbalLoader = new \Doctrine\Common\ClassLoader('Doctrine\DBAL', 'doctrine');
    $autoloader->pushAutoloader(array($dbalLoader, 'loadClass'), 'Doctrine\DBAL');

    $ormLoader = new \Doctrine\Common\ClassLoader('Doctrine\ORM', 'doctrine');
    $autoloader->pushAutoloader(array($ormLoader, 'loadClass'), 'Doctrine\ORM');

    $modelLoader = new \Doctrine\Common\ClassLoader(NULL, APPLICATION_PATH . "/models");
    $autoloader->pushAutoloader(array($modelLoader, 'loadClass'), '');

    // create the Doctrine configuration
    $config = new \Doctrine\ORM\Configuration();

    // setting the cache ( to ArrayCache. Take a look at
    // the Doctrine manual for different options ! )
    $cache = new \Doctrine\Common\Cache\ArrayCache;
    $config->setMetadataCacheImpl($cache);
    $config->setQueryCacheImpl($cache);

    // choosing the driver for our database schema
    // we'll use annotations
    $driver = $config->newDefaultAnnotationDriver(
        APPLICATION_PATH . '/models'
        );
    $config->setMetadataDriverImpl($driver);

    // set the proxy dir and set some options
    $config->setProxyDir(APPLICATION_PATH . '/models/Proxies');
    $config->setAutoGenerateProxyClasses(true);
    //$config->setAutoGenerateProxyClasses(false);
    $config->setProxyNamespace('App\Proxies');

    // now create the entity manager and use the connection
    // settings we defined in our application.ini
    $connectionSettings = $this->getOption('doctrine');
    $conn = array(
    'driver'    => $connectionSettings['conn']['driv'],
    'user'      => $connectionSettings['conn']['user'],
    'password'  => $connectionSettings['conn']['pass'],
    'dbname'    => $connectionSettings['conn']['dbname'],
    'host'      => $connectionSettings['conn']['host']
    );
    $entityManager = \Doctrine\ORM\EntityManager::create($conn, $config);

    // push the entity manager into our registry for later use
    $registry = Zend_Registry::getInstance();
    $registry->entitymanager = $entityManager;

    return $entityManager;
}

Когда я добавляю

namespace models;

для каждого из моих классов моделей и обновить Bootstrap следующим образом. Я получаю исключение «Приложение класса не существует» (приложение является одной из моих моделей):

$modelLoader = new \Doctrine\Common\ClassLoader('models', APPLICATION_PATH . "/models");
$autoloader->pushAutoloader(array($modelLoader, 'loadClass'), 'models');

Просто для полноты я ссылаюсь на эту модель в своем контроллере следующим образом:

public function indexAction()
{
    $this->_helper->layout()->title = "Your applications";
    $this->_helper->layout()->description = "Create, edit and view all applications you have registered with us.";
    $this->view->applicationList = $this->entityManager->getRepository("Application")->findAll();
}

Что мне не хватает? Я уверен, что это очевидно, но сейчас я действительно рву на себе волосы.


person Sabooji    schedule 02.06.2012    source источник


Ответы (1)


После долгих поисков я наткнулся на это видео (требуется авторизация).

По сути, способ, которым я решил (согласно вебинару), заключался в том, чтобы создать пространство имен для моих объектов и сохранить их в каталоге /library. Затем, когда мне нужно использовать их из реального приложения, я получаю доступ через их пространство имен.

person Sabooji    schedule 14.06.2012