Codeigniter 2.2 and Doctrine 2

Asked

Viewed 98 times

3

I have installed CI2, Doctrine 2 and HMVC. I followed the steps of this website except for Smarty that I didn’t find necessary.

My folders are organized as follows:

->application

  ->cache
    ->doctrine
      ->generated_entities
      ->proxies

  ->core
    ->MY_Loader.php
    ->MY_Router.php
    ->MY_Controller.php

  ->libraries
    ->Doctrine.php

  ->models
    ->doctrine
      ->entities
        ->usuario.php
        ->grupo.php

  ->third_party
    ->Doctrine
      ->bin
      ->Doctrine
        ->Common
        ->DBAL
        ->ORM
        ->Symfony

  ->...

My autoload.php file I inserted the Doctrine:

$autoload['libraries'] = array('session', 'bcrypt', 'doctrine');

In the Doctrine file of the library folder I have this code:

<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
use Doctrine\Common\ClassLoader,
    Doctrine\ORM\EntityManager,
    Doctrine\ORM\Configuration,
    Doctrine\ORM,
    Doctrine\Common\Cache\ArrayCache,
    Doctrine\DBAL\Logging\EchoSQLLogger,
    Doctrine\ORM\Mapping\Driver\DatabaseDriver,
    Doctrine\ORM\Tools\DisconnectedClassMetadataFactory,
    Doctrine\ORM\Tools\EntityGenerator,
    Doctrine\OXM;

define('DEBUGGING', false);
/**
 * Doctrine
 *
 * @category Libraries
 * @package  CodeIgniter
 * @author   Tariqul Islam <[email protected]>
 * @license  http://directory.fsf.org/wiki/License:ReciprocalPLv1.3 Reciprocal Public License v1.3
 * @link     http://webkutir.net
 */

class Doctrine
{
    public $em = null;
    /**
     * Class Constructor
     */
    public function __construct()
    {
        // load database configuration and custom config from CodeIgniter
        include APPPATH . 'config/database.php';
        // Set up class loading.
        include_once APPPATH . 'third_party/Doctrine/Doctrine/Common/ClassLoader.php';
        $doctrineClassLoader = new \Doctrine\Common\ClassLoader('Doctrine', APPPATH . 'third_party/Doctrine');
        $doctrineClassLoader->register();
        $entitiesClassLoader = new \Doctrine\Common\ClassLoader('entities', APPPATH . 'models/doctrine');
        $entitiesClassLoader->register();
        $proxiesClassLoader = new \Doctrine\Common\ClassLoader('proxies', APPPATH . 'cache/doctrine');
        $proxiesClassLoader->register();
        $symfonyClassLoader = new \Doctrine\Common\ClassLoader('Symfony', APPPATH . 'third_party/Doctrine/Doctrine');
        $symfonyClassLoader->register();
        // Choose caching method based on application mode (ENVIRONMENT is defined in /index.php)
        if (ENVIRONMENT == 'development' || ENVIRONMENT == 'testing') {
            $cache = new \Doctrine\Common\Cache\ArrayCache;
        } else {
            $cache = new \Doctrine\Common\Cache\ApcCache;
        }
        // Set some configuration options
        $config = new Configuration;
        // Metadata driver
        $driverImpl = $config->newDefaultAnnotationDriver(APPPATH . 'models/doctrine/entities');
        $config->setMetadataDriverImpl($driverImpl);
        // Caching
        $config->setMetadataCacheImpl($cache);
        $config->setQueryCacheImpl($cache);
        // Proxies
        $config->setProxyDir(APPPATH . 'cache/doctrine/proxies');
        $config->setProxyNamespace('Proxies');
        if (ENVIRONMENT == 'development') {
            $config->setAutoGenerateProxyClasses(true);
        } else {
            $config->setAutoGenerateProxyClasses(false);
        }
        // SQL query logger
        if (DEBUGGING) {
            $logger = new \Doctrine\DBAL\Logging\EchoSQLLogger;
            $config->setSQLLogger($logger);
        }
        // Database connection information
        if (ENVIRONMENT == 'testing') {
            $active_group = 'default_test';
        }
        $connectionOptions = array(
            'driver'   => 'pdo_mysql',
            'user'     => $db[$active_group]['username'],
            'password' => $db[$active_group]['password'],
            'host'     => $db[$active_group]['hostname'],
            'dbname'   => $db[$active_group]['database']
        );
        // Create EntityManager
        $this->em = EntityManager::create($connectionOptions, $config);
        //Classe para criar o banco
        //$this->generate_classes();
    }

    /**
    * generate entity objects automatically from mysql db tables
    * @return none
    */
    function generate_classes(){
        $this->em->getConfiguration()
            ->setMetadataDriverImpl(
                new DatabaseDriver(
                $this->em->getConnection()->getSchemaManager()
            )
        );
        $cmf = new DisconnectedClassMetadataFactory();
        $cmf->setEntityManager($this->em);
        $metadata = $cmf->getAllMetadata();     
        $generator = new EntityGenerator();
        $generator->setUpdateEntityIfExists(true);
        $generator->setGenerateStubMethods(true);
        $generator->setGenerateAnnotations(true);
        $generator->generate($metadata, APPPATH."models/doctrine/entities");
    }
}

/* End of file Doctrine.php */
/* Location: ./application/libraries/Doctrine.php */

As I am using HMVC, in core folder, in application, I created three file, which follows:

My_loader.php

<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

/* load the MX_Loader class */
require APPPATH."third_party/MX/Loader.php";

class MY_Loader extends MX_Loader {}

My_router.php

<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

/* load the MX_Router class */
require APPPATH."third_party/MX/Router.php";

class MY_Router extends MX_Router {}

My_controller

<?php (defined('BASEPATH')) OR exit('No direct script access allowed');
/**
 * MY_Controller
 *
 * @category MY_Controller
 * @package  CodeIgniter
 * @author   Tariqul Islam <[email protected]>
 * @license  http://directory.fsf.org/wiki/License:ReciprocalPLv1.3 Reciprocal Public License v1.3
 * @link     http://webkutir.net
 */
class MY_Controller extends MX_Controller
{
    public $em;
    /**
     * Constructor of MY Controller
     */
    function __construct()
    {
        parent::__construct();
        $this->em=$this->doctrine->em;
    }
}

/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */

Follow the.php user and group.php files inside the entities folder:

php user.

<?php

/**
 * Usuario
 *
 * @Table(name="usuario")
 * @Entity
 */
class Usuario
{
    /**
    * @Id @Column(type="integer")
    * @GeneratedValue(strategy="IDENTITY")
    */
    public $id = 0;
    /**
    * @var string
    * @Column(name="nome", type="string", length=50, nullable=true)
    */
    public $nome = '';
    /**
    * @var string
    * @Column(name="login", type="string", length=20, nullable=true)
    */
    public $login = '';
    /**
    * @var string
    * @Column(name="senha", type="string", length=300, nullable=true)
    */
    public $senha = '';
    /**
    * @var boolean
    * @Column(name="ativo", type="boolean", nullable=true, options={"default":0})
    */
    public $ativo = 0;
    /**
    * @var string
    * @Column(name="email", type="string", length=200, nullable=true)
    */
    public $email = '';
    /**
    * @var string
    * @Column(name="fone_primeiro", type="string", length=14, nullable=true)
    */
    public $fone_primeiro = '';
    /**
    * @var string
    * @Column(name="fone_segundo", type="string", length=14, nullable=true)
    */
    public $fone_segundo = '';
    /**
    * @var string
    * @Column(name="esqueci_senha_cod", type="string", length=40, nullable=true)
    */
    public $esqueci_senha_cod = '';
    /**
    * @var DateTime
    * @Column(name="ultimo_acesso", type="datetime", nullable=true)
    */
    public $ultimo_acesso = '';
    /**
    * @var boolean
    * @Column(name="online", type="boolean", nullable=true, options={"default":0})
    */
    public $online = 0;
    /**
    * @var string
    * @Column(name="usuario_cad", type="string", length=15, nullable=true)
    */
    public $usuario_cad = '';
    /**
    * @var string
    * @Column(name="usuario_alt", type="string", length=15, nullable=true)
    */
    public $usuario_alt = '';
    /**
    * @var DateTime
    * @Column(name="dt_entrada", type="datetime", nullable=true)
    */
    public $dt_entrada = '';
    /**
    * @var DateTime
    * @Column(name="dt_saida", type="datetime", nullable=true)
    */
    public $dt_saida = '';
    /**
    * @var Grupo
    *
    * @ManyToOne(targetEntity="Grupo")
    * @JoinColumn(name="grupo_id", referencedColumnName="id")
    */
    public $grupo;
    /**
    * Constructor
    */
    public function __construct()
    {
        $this->ultimo_acesso = new \DateTime("now");
        $this->dt_entrada = new \DateTime("now");
        $this->dt_saida = new \DateTime("now");
    }
}
/* End of file usuario.php */
/* Location: ./application/model/usuario.php */

php group.

<?php

/**
 * Grupo
 *
 * @Table(name="grupo")
 * @Entity
 */
class Grupo
{
    /**
    * @Id @Column(type="integer")
    * @GeneratedValue(strategy="IDENTITY")
    */
    public $id = 0;
    /**
    * @var string
    * @Column(name="nome", type="string", length=10, nullable=false)
    */
    public $nome = '';
    /**
    * @var string
    * @Column(name="apelido", type="string", length=20, nullable=false)
    */
    public $apelido = '';
    /**
    * @var boolean
    * @Column(name="ativo", type="boolean", nullable=false, options={"default":0})
    */
    public $ativo = 0;
    /**
    * @var string
    * @Column(name="usuario_cad", type="string", length=15, nullable=false)
    */
    public $usuario_cad = '';
    /**
    * @var string
    * @Column(name="usuario_alt", type="string", length=15, nullable=false)
    */
    public $usuario_alt = '';
    /**
    * @var DateTime
    * @Column(name="dt_cad", type="datetime", nullable=false)
    */
    public $dt_cad = '';
    /**
    * @var DateTime
    * @Column(name="dt_alt", type="datetime", nullable=false)
    */
    public $dt_alt = '';
    /**
    * metodo construtor
    **/
    public function __construct()
    {
        $this->dt_cad = new \DateTime("now");
        $this->dt_alt = new \DateTime("now");
    }
}
/* End of file grupo.php */
/* Location: ./application/model/doctrine/entities/grupo.php */

Below is my controller with the code that creates the tables in the database:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Teste2 extends MY_Controller {

    private $st;
    private $cmf;

    function __construct()
    {
        //Chama o modelo construtor
       parent::__construct();

        $this->st = new \Doctrine\ORM\Tools\SchemaTool($this->doctrine->em);
        $this->cmf = $this->doctrine->em->getMetadataFactory();
    }

    public function index()
    {
        try {
            //$this->st->createSchema($this->cmf->getAllMetadata());
            $saveMode=false;
            $this->st->updateSchema($this->cmf->getAllMetadata(), $saveMode);
        } catch(Exception $ex) {

        }
    }
}

/* End of file teste2.php */
/* Location: ./application/controllers/teste2.php */

So, for example, in a controller I create users:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Teste extends MY_Controller {

    function __construct()
    {
        //Chama o modelo construtor
       parent::__construct();
    }

    public function index()
    {
        //======== CAD GRUPO
        $this->load->model('doctrine/entities/grupo', 'grupo');
        $this->grupo->nome = 'user';
        $this->grupo->apelido = 'Usuário';
        $this->grupo->ativo = 1;
        $this->grupo->usuario_cad = 'user';
        $this->grupo->usuario_alt = 'user';

        $this->doctrine->em->persist($this->grupo);

        //======= CAD USUARIO
        $this->load->model('doctrine/entities/usuario', 'usuario');

        $this->usuario->nome = 'wagner';
        $this->usuario->login = 'wagner';
        $this->usuario->senha = 'wagner';
        $this->usuario->ativo = 1;
        $this->usuario->grupo = $this->grupo;

        $this->doctrine->em->persist($this->usuario);

        $this->doctrine->em->flush();
    }
}

/* End of file teste.php */
/* Location: ./application/controllers/teste.php */

And in another file I try to make a query of this user, but that’s where the problem happens.

If I just search, it returns an error like this: 500 - Internal Server Error. Follow the file:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends MY_Controller {

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }

    function index()
    {
        $this->load->model('doctrine/entities/usuario', 'usuario');
        $usuario = $this->em->getRepository("usuario")->find(1);
        var_dump($usuario->login);
    }

}

/* End of file login.php */
/* Location: ./application/controllers/login.php */

Since I’m new to Doctrine, I started to tinker here and there and added some code in the example above and it worked. But why? What’s wrong with my Code? Follow the new code:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends MY_Controller {

private $st;
private $cmf;

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();

        $this->st = new \Doctrine\ORM\Tools\SchemaTool($this->doctrine->em);
        $this->cmf = $this->doctrine->em->getMetadataFactory();
    }

    function index()
    {
        try {
            $saveMode=false;
            $this->st->updateSchema($this->cmf->getAllMetadata(), $saveMode);
        } catch(Exception $ex) {

        }

        $this->load->model('doctrine/entities/usuario', 'usuario');
        $usuario = $this->em->getRepository("usuario")->find(1);
        var_dump($usuario->login);
    }

}

/* End of file login.php */
/* Location: ./application/controllers/login.php */

So if you can tell me what I’m doing wrong.

Another interesting thing that I realized, is that in these codes that I posted, I’m using Manytoone Unidirectional. So if I do a simple search on an entity that has no relationship, the code works without using that schema.

Then I know nothing more of anything!! rsrsr

I thank you and I apologize if it is something easy, but as I do not have much knowledge of Doctrine and I already searched Google and found nothing, I thought to ask.

Thank you.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.