Учение 2 Не могу найти энтитов - PullRequest
0 голосов
/ 26 декабря 2010

Я использую Kohana 3 и у меня есть папка / doctrine / Entites с моими сущностями внутри.При выполнении кода

$product = Doctrine::em()->find('Entities\Product', 1);

в моем контроллере я получаю ошибку

class_parents(): Class Entities\Product does not exist and could not be loaded

Ниже представлен контроллер (classes / controller / welcome.php):

<?php

class Controller_Welcome extends Controller {

    public function action_index()
    {
        $prod = Doctrine::em()->find('Entities\Product', 1);
    }

}

Ниже находится объект (/doctrine/Entities/Product.php):

<?php

/**
 * @Entity
 * @Table{name="products"}
 */
class Product
{
    /** @Id @Column{type="integer"} */
    private $id;
    /** @Column(type="string", length="255") */
    private $name;

    public function getId() { return $this->id; }
    public function setId($id) { $this->id = intval($id); }
    public function getName() { return $this->name; }
    public function setName($name) { $this->name = $name; }
}

Ниже приведен файл начальной загрузки модуля Doctrine (/modules/doctrine/init.php):

class Doctrine
{
    private static $_instance = null;
    private $_application_mode = 'development';
    private $_em = null;

    public static function em()
    {
        if ( self::$_instance === null )
            self::$_instance = new Doctrine();

        return self::$_instance->_em;
    }

    public function __construct()
    {
        require __DIR__.'/classes/doctrine/Doctrine/Common/ClassLoader.php';

        $classLoader = new \Doctrine\Common\ClassLoader('Doctrine', __DIR__.'/classes/doctrine');
        $classLoader->register();
        $classLoader = new \Doctrine\Common\ClassLoader('Symfony', __DIR__.'/classes/doctrine/Doctrine');
        $classLoader->register();
        $classLoader = new \Doctrine\Common\ClassLoader('Entities', APPPATH.'doctrine');
        $classLoader->register();

        //Set up caching method
        $cache = $this->_application_mode == 'development'
            ? new \Doctrine\Common\Cache\ArrayCache
            : new \Doctrine\Common\Cache\ApcCache;

        $config = new Configuration;
        $config->setMetadataCacheImpl( $cache );
        $driver = $config->newDefaultAnnotationDriver( APPPATH.'doctrine/Entities' );
        $config->setMetadataDriverImpl( $driver );
        $config->setQueryCacheImpl( $cache );

        $config->setProxyDir( APPPATH.'doctrine/Proxies' );
        $config->setProxyNamespace('Proxies');
        $config->setAutoGenerateProxyClasses( $this->_application_mode == 'development' );

        $dbconf = Kohana::config('database');
        $dbconf = reset($dbconf); //Use the first database specified in the config

        $this->_em = EntityManager::create(array(
            'dbname'     => $dbconf['connection']['database'],
            'user'         => $dbconf['connection']['username'],
            'password'     => $dbconf['connection']['password'],
            'host'         => $dbconf['connection']['hostname'],
            'driver'     => 'pdo_mysql',
        ), $config);
    }
}

Есть идеи, что я сделал не так?

Ответы [ 3 ]

3 голосов
/ 26 декабря 2010

ОБНОВЛЕНИЕ: объекты пространства имен; должно быть в начале каждой сущности

Это что-то с автозагрузчиком. Я очень новичок в Доктрине 2 (даже новичок в 1.2), но я думаю, что это в вашем:

    $classLoader = new \Doctrine\Common\ClassLoader('Entities', APPPATH.'doctrine');
    $classLoader->register();

Попробуйте добавить реальный путь (APPPATH. 'Doctrine'). Я использую Zend Framework, поэтому он выглядит немного иначе в начальной загрузке, но, возможно, это поможет:

/**
 * Initialize auto loader of Doctrine
 *
 * @return Doctrine_Manager
 */
protected function _initDoctrine() {
    $this->bootstrap('autoload');

    require_once('Doctrine/Common/ClassLoader.php');

    /*
      $classLoader = new \Doctrine\Common\ClassLoader('Doctrine');
      $classLoader->setIncludePath(APPLICATION_PATH . '/../library/');
      $classLoader->register();/* */

    // Create the doctrine autoloader and remove it from the spl autoload stack (it adds itself)
    require_once 'Doctrine/Common/ClassLoader.php';
    $doctrineAutoloader = array(new \Doctrine\Common\ClassLoader(), 'loadClass');
    //$doctrineAutoloader->register();
    spl_autoload_unregister($doctrineAutoloader);

    $autoloader = Zend_Loader_Autoloader::getInstance();

    // Push the doctrine autoloader to load for the Doctrine\ namespace
    $autoloader->pushAutoloader($doctrineAutoloader, 'Doctrine');

    $classLoader = new \Doctrine\Common\ClassLoader('Entities', realpath(__DIR__ . '/models/'), 'loadClass');
    $autoloader->pushAutoloader(array($classLoader, 'loadClass'), 'Entities');

    $classLoader = new \Doctrine\Common\ClassLoader('Symfony', realpath(__DIR__ . '/../library/Doctrine/'), 'loadClass');
    $autoloader->pushAutoloader(array($classLoader, 'loadClass'), 'Symfony');

    $doctrineConfig = $this->getOption('doctrine');
    $config = new \Doctrine\ORM\Configuration();

    $cache = new \Doctrine\Common\Cache\ArrayCache;
    $config->setMetadataCacheImpl($cache);
    $config->setQueryCacheImpl($cache);

    $driverImpl = new Doctrine\ORM\Mapping\Driver\YamlDriver(APPLICATION_PATH . '/configs/mappings/yaml');
    //$driverImpl = $config->newDefaultAnnotationDriver($doctrineConfig['path']['entities']);
    $config->setMetadataDriverImpl($driverImpl);

    //$driverImpl = $config->newDefaultAnnotationDriver(
    //       array($doctrineConfig['paths']['entities']));
    //$config->setMetadataDriverImpl($driverImpl);

    $config->setProxyDir(APPLICATION_PATH . '/../proxies');
    $config->setProxyNamespace('App\Proxies');

    $connectionOptions = array(
        'driver' => $doctrineConfig['conn']['driv'],
        'user' => $doctrineConfig['conn']['user'],
        'password' => $doctrineConfig['conn']['pass'],
        'dbname' => $doctrineConfig['conn']['dbname'],
        'host' => $doctrineConfig['conn']['host']
    );


    $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);

    $eventManager = $em->getEventManager();
    $eventManager->addEventSubscriber(new Maxlib_EventSubscriber_Sortable());

    $registry = Zend_Registry::getInstance();
    $registry->entitymanager = $em;


    return $em;
}
1 голос
/ 26 декабря 2010

Оказывается, мне пришлось добавить

namespace Entities;

к началу файла сущностей. Это не было написано ни в одном из учебных пособий. Спасибо пользователю Max за помощь в IRC.

0 голосов
/ 21 ноября 2011

Просто чтобы прояснить ответ Макса Гордона, это то, что сработало для меня

Если у вас есть ваши энтиты внутри / модели / с «сущностями пространства имен» вверху

$classLoader = new \Doctrine\Common\ClassLoader('Entities', realpath(APPLICATION_PATH . '/models/'), 'loadClass');
$classLoader->register();

или сzend

$classLoader = new \Doctrine\Common\ClassLoader('Entities', realpath(APPLICATION_PATH . '/models/'), 'loadClass');
$autoloader = Zend_Loader_Autoloader::getInstance();     
$autoloader->pushAutoloader(array($classLoader, 'loadClass'), 'Entities');
...