Doctrine

Install Doctrine With Zend Framework 2

In this tutorial we are going to learn how you can install doctrine into your Zend Framework 2 application.

What Is Zend Framework 2?

zend-framework Zend framework is one of the most popular PHP frameworks created for high performing PHP applications. It is an open source project supported by Zend Technologies. Zend Framework uses 100% object-oriented approach to PHP development and uses most of the new features available to PHP including PHP namespaces, late static binding classes and closures.

It recently had a huge overhaul of code changes with the new Framework 2, now based of having code modules that you can include in your application. A module is like a plugin, you can drop this module into your application, enable the module and have access to all the features that this module allows you to have. The advantages of using modular code like this is that you can easily reuse this in other applications.

Therefore you could create a standard module to login to the application, for all your future applications you can simply reuse this module and you now take this functionality with you.

Zend Framework 2 is very extendable and flexible you will be able to create any type of website that you want. Using the MVC implementation Zend allows you to apply database abstraction in your application, decoupling the database and your presentation.

With most open source projects there is a strong community of developers that help with support questions, Zend Framework is no different there is a very active support community available for anyone stuck on both simple or difficult questions.

A big improvement in Zend Framework 2 is the use of PHPunit to test all the core code, this comes packaged with the framework making it very easy for you to test your own applications using PHPunit, giving you a test driven development approach to creating your application.

To try out the framework on your next project you can download it here.

Zend Framework 2

This tutorial assumes that you have an already installed version of Zend Framework, ready to start developing. If you need information about how to get started with Zend, follow this tutorial.

Getting Started With Zend Framework 2

What Is The Doctrine Project?

Doctrine is a set of PHP class libraries that are focused on database storage and database management. The main projects with Doctrine are the ORM (Object Relational Manager) and DBAL (Database Abstraction Layer). Using these two projects Doctrine allows you to build up database entities in PHP code that will represent your application's database structure.

Having PHP classes to construct your database structure means that you can use fully object oriented code to construct the Database queries, this provides developers with a powerful alternative to SQL that maintains flexibility without requiring unnecessary code duplication.

Doctrine

Installing With Composer

The easiest way to install Doctrine into your Zend Framework application is to use the PHP project composer.

Composer is a dependency manager for PHP allowing you to state what third party projects your application will depend on to work correctly. This will be populated into a composer config JSON file. Using this JSON file composer will automatically get the any version of the repository and install the code into your application.

As our Zend application will have a Database dependency of Doctrine we need to ensure that this is included in our application.

To install the doctrine project in your application use the following command.

php composer.phar require doctrine/doctrine-orm-module:0.8.*

This has now downloaded all the files needed for doctrine and placed it inside the /vendor folder in your Zend Application.

To monitor the queries that the database is making the Zend Framework Developer Tools can be very useful, use the following composer command to install the repository.

php composer.phar require zendframework/zend-developer-tools:dev-master

When the Zend Developer Tools have installed you need to move the configuration file into your application config.

cp vendor/zendframework/zend-developer-tools/config/zenddevelopertools.local.php.dist config/autoload/zdt.local.php

With Doctrine code installed in your application you need to enable the Doctrine modules with Zend.

Open you application config file and add the new modules to the module array config/application.config.php

return array(
    'modules' => array(
        'ZendDeveloperTools',
        'DoctrineModule',
        'DoctrineORMModule',
        'Application',
    ),
    // [...]
);

Doctrine is now installed in your Zend application and you can start adding the entities you need to create the doctrine database.

Create Your First Entity

Create a folder where you want to store your application entities, can be in an existing module or in a new module for your entities.

Inside the entity folder create a new PHP file called User.php, this class will be used to define the structure of the User entity and database structure for the user table.

<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;

/** @ORM\Entity */
class User
{
    /**
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    * @ORM\Column(type="integer")
    */
    protected $id;

    /** @ORM\Column(type="string") */
    protected $Name;
}
[/php]

Next you will need to tell Doctrine where to find your entities in your file structure, open the Zend module config file <strong>/config/module.config.php</strong> and paste the following code.

[php]
<?php
namespace Application;

return array(
    'doctrine' => array(
        'driver' => array(
            __NAMESPACE__ . '_driver' => array(
                'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
                'cache' => 'array',
                'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity',  // Define path of entities
                )
            ),
            'orm_default' => array(
                'drivers' => array(
                    __NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'  // Define namespace of entities
                )
            )
        )
    ),
);

If the entity has been successfully mapped to Doctrine then you will see this defined on the Zend Developer Toolbar.

user-mapping

Connecting To The Database

With an entity created we can now connect to the database and get Doctrine to use the entity defined to create the database structure.

In your Zend application config/autoload folder create a new file named doctrine.local.php and paste in the following code, changes the settings with your database login.

<?php
return array(
    'doctrine' => array(
        'connection' => array(
            'orm_default' => array(
                'driverClass' =>'Doctrine\DBAL\Driver\PDOMySql\Driver',
                'params' => array(
                    'host'     => 'localhost',
                    'port'     => '',
                    'user'     => 'user',
                    'password' => 'pass',
                    'dbname'   => 'data',
                )))));

To check that the PHP entities and database structures are mapped correctly you can validation the schema by running the following command.

vendor/bin/doctrine-module orm:validate-schema

This will show you that the entity files are setup correctly but the database schema does not match up with the entities.

validate-doctrine-schema

Now we can create the database by running the following command.

vendor/bin/doctrine-module orm:schema-tool:create

After running this command you can now switch to your database and you should see the user table with the columns we defined in the entity.

user-database

With the table and Doctrine entity created we can now use this in our application to add data to the table. For this you need to use the Zend service locator to get the entity manager, then you can create a new instance of the user entity, populate the entity and use the entity manager to add the data to the database.

Below is the example code of how you can use the entity manager to populate new rows into your database.

<?php
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    public function indexAction() {
        $entityManager = $this
            ->getServiceLocator()
            ->get('Doctrine\ORM\EntityManager');

        $user = new \Application\Entity\User();
        $user->setName('Paul Underwood');

        $entityManager->persist($user);
        $entityManager->flush();

        echo $user->getId();

        return new ViewModel();
    }
}

If the query was successful then this code should output a number 1 on the view and the database will have the new user of Paul Underwood in the first row.

This is a simple example of getting Doctrine setup in your application you can now take this info your next project and develop a website in Zend with Doctrine powering the database.

Back to top

Fastest WordPress Hosting With WPEngine

Stunning speed, powerful security, and best-in-class customer service. At WP Engine.

Risk free for 60 days