Install Codeigniter 3 with Doctrine and Composer

Asked

Viewed 2,008 times

8

What is the best way to install via in the 3.0? I plan to leave the files in the folder libraries.

I created the file composer.json:

{
    "config": {
        "vendor-dir": "application/libraries"
    },
    "require": {
        "doctrine/common": "2.4.*",
        "doctrine/dbal": "2.4.*",
        "doctrine/orm": "2.4.*" 
    }
}

I executed the command php composer.phar install, creating the files inside the folder application/libraries in Codeigniter 3.0.

I created a library called Doctrine.php and added to the autoload:

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

The doctrine.php:

<?php
//AutoLoader do Composer
$loader = require __DIR__.'/vendor/autoload.php';
//vamos adicionar nossas classes ao AutoLoader
$loader->add('Pasta_library', __DIR__);


use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;

//se for falso usa o APC como cache, se for true usa cache em arrays
$isDevMode = false;

//caminho das entidades
$paths = array(__DIR__ );
// configurações do banco de dados
$dbParams = array(
    'driver'   => 'pdo_mysql',
    'user'     => 'root',
    'password' => '',
    'dbname'   => 'dnp',
);

$config = Setup::createConfiguration($isDevMode);

//leitor das annotations das entidades
$driver = new AnnotationDriver(new AnnotationReader(), $paths);
$config->setMetadataDriverImpl($driver);
//registra as annotations do Doctrine
AnnotationRegistry::registerFile(
    __DIR__ . '/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'
);
//cria o entityManager
$entityManager = EntityManager::create($dbParams, $config);

When trying to upload the project, the error messages appear:

Fatal error: require(): Failed Opening required '/Users/israel/Sites/agemed/application/Libraries/vendor/autoload.php' (include_path='.:/usr/local/php5/lib/php') in /Users/israel/Sites/agemed/application/Libraries/Doctrine.php on line 3

Showing that the system is not locating the correct path.

Where to correct?

  • Doctrine.php is in which project folder ?

1 answer

5


TL;DR

I climbed into the Github an example project integrating Codeigniter 3 with Doctrine, accompanied by an example.


The error is in the way you use the self-loading.

In the archive doctrine.php the correct on line 3 would be:

$loader = require APPPATH . 'vendor/autoload.php';

But include in the nail the autoload within the Doctrine.php is unnecessary in Codeigniter 3. It has a configuration that already injects the autoload of Composer in our application.

Configure the file config.php

$config['composer_autoload'] = TRUE;

Or if you prefer to use the folder vendor at the root of the project (my case), enter the path to the autoload.php.

$config['composer_autoload'] = 'vendor/autoload.php';

Using the second option we can take from our composer.json a config "vendor-dir" : "application/libraries".


My file libraries\Doctrine.php is a little different too. I used a based file in Soen’s reply.

<?php

use Doctrine\Common\ClassLoader,
    Doctrine\ORM\Tools\Setup,
    Doctrine\ORM\EntityManager;

class Doctrine
{
    public $em;

    public function __construct()
    {
        // Load the database configuration from CodeIgniter
        require APPPATH . 'config/database.php';

        $connection_options = array(
            'driver'        => 'pdo_mysql',
            'user'          => $db['default']['username'],
            'password'      => $db['default']['password'],
            'host'          => $db['default']['hostname'],
            'dbname'        => $db['default']['database'],
            'charset'       => $db['default']['char_set'],
            'driverOptions' => array(
                'charset'   => $db['default']['char_set'],
            ),
        );

        // With this configuration, your model files need to be in application/models/Entity
        // e.g. Creating a new Entity\User loads the class from application/models/Entity/User.php
        $models_namespace = 'Entity';
        $models_path = APPPATH . 'models';
        $proxies_dir = APPPATH . 'models/Proxies';
        $metadata_paths = array(APPPATH . 'models');

        // Set $dev_mode to TRUE to disable caching while you develop
        $config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode = true, $proxies_dir);
        $this->em = EntityManager::create($connection_options, $config);

        $loader = new ClassLoader($models_namespace, $models_path);
        $loader->register();
    }
}

To use the Doctrine, create a folder Entity inside models and insert your Entities inside the namespace Entity

<?php namespace Entity;

/**
 * @Entity @Table(name="products")
 **/
class Product
{
    /** @Id @Column(type="integer") @GeneratedValue **/
    protected $id;
    /** @Column(type="string") **/
    protected $name;

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }
}

After including the Doctrine.php in the autoload codeigniter ($autoload['libraries'] = array('doctrine');) I can use the Entity in my controller.

public function index()
{
    $product = new Entity\Product();

    $product->setName('Teste');

    $this->doctrine->em->persist($product);
    $this->doctrine->em->flush();       
}
  • Israel, you got the idea?

Browser other questions tagged

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