Technology + People + Process

Integrating Doctrine into PHP Project

Integrating Doctrine into PHP Project

Doctrine: The Doctrine is a set of PHP libraries primarily focused on providing persistance services and related functionality. Its prize projects are an Object Relational Mapper (ORM) and the Database Abstraction Layer it is built on top of.

One of Doctrine's key features is the option to write database queries in a proprietary object oriented SQL dialect called Doctrine Query Language (DQL).

Doctrine instatllation :

  • Download latest Doctrine ORM source code from the below URL https://github.com/doctrine/doctrine2
  • After downloading the source code we have include the Doctrine into our project as below

// Including Doctine Base class

require_once('includes/lib/Doctrine.php');

spl_autoload_register ( array ('Doctrine','autoload'));

//create the singleton Doctrine_Manager instance and assign it to a variable named $manager:

$manager = Doctrine_Manager::getInstance();

// Connecting to database

$conn = Doctrine_Manager::connection('mysql://' . $userName . ':' . $password . '@' . $hostName . '/' . $dbName,'connection1');

$conn->setCharset('utf8');

//Code to Autoload models no need to manually include generated classes

$manager->setAttribute(Doctrine::ATTR_MODEL_LOADING, Doctrine::MODEL_LOADING_CONSERVATIVE);

Doctrine::loadModels($MyClassGenerated);

Doctrine::loadModels($MyClass);

 3.  Doctrine will generate models automatically for every table in our DB. For this feature we have to include one line after the above lines.

       Doctrine::generateModelsFromDb('includes/myclasses');

 4.  After this we can use those models and write the queries using Doctrine Query language(DQL).

 5.  Where ever we want to use the models or database related query we want to include the models like 

              require_once($MyClass . 'Ads.php'); 

              Here 'Ads' is the table name and Ads.php is the model that automatically generated.

 6.  DQL:

Insert Query using DQL :

Let us take Ads is our model

$insert = new Ads();

        $insert->name = ‘ad’;

$insert->save();

Select query using DQL :

$selectQuery = Doctrine_Query::create()   

->select('*')

->from('Ads')

->where('name=?',’ad‘);

To Fetch the array

$selectName = $selectQuery->fetchArray();

Update query using DQL :

$updateAdQuery = Doctrine_Query::create()            

->update('Ads')

->set('name','?',’ad1‘);

To execute the query

$updateAdQuery1->execute();

Delete Query using DQL :

$deleteAdQuery = Doctrine_Query::create()

    ->delete('Ads')

    ->where('ad_id=?',1);

Writing Inner JOIN query using DQL :

$innerJoinQuery = Doctrine_Query::create()

->select('v.v_id,s1.s_v_name,v.v_name')

->from('Vertical v')

->innerJoin('v.SubVertical s1')

->where('s1.s_v_id = ?',1);

To fetch the data

$selectRes = $innerJoinQuery->fetchArray();


Request for Quote

Drop us a line and we'll get in touch with you as quick as we can