Learn Yaml with Doctrine in a Zend 3 project

It’s been some time I planed on talking about Yaml and more precisely about its use for Mysql configuration tables and Entity generation.

So today we will overview Yaml for Mysql automatic table integration using Doctrine and Zend 3. If you have never heard about Yaml, well you are better late than never !

What is Yaml ?

First off, Yaml stands for YAML Ain’t Markup Language. It’s a data serialization language and its main purpose is to be human friendly and thus be easily and quickly understandable by any people. For a more details description, check out the Yaml specifications on Yaml.org.

There are plenty of tutorials on using Yaml on the internet so we are going here to focus only on Doctrine Mapping with Yaml.

Using Yaml with Doctrine

We can apply Yaml integration along with Doctrine not only on Zend Framework, a Yaml file in this case is used as a schema which includes the model definitions and classes. This file is parsed to a tool to automatically handle the corresponding requests.

Basically using Yaml will ease the work and portability of your model.

Let’s add an example of a table we need in Mysql along with its entity.

Install Yaml

Yaml is a component from the symfony framework and we install the package using composer :

$ composer require symfony/yaml

Add the package inside the composer.json file :

/*..*/

"require" : {
"php" : "^5.6 || ^7.0",
"zendframework/zend-component-installer" : "^1.0 || ^0.7 || ^1.0.0-dev@dev",
"zendframework/zend-mvc" : "^3.1",
"zfcampus/zf-development-mode" : "^3.0",
"doctrine/doctrine-orm-module" : "^1.1",
"symfony/yaml" : "^3.0",

/*..*/

then run :

$ composer update

That last command will generate the autoload files.

And inside my module.config.php configuration file :


        'doctrine' => [

                // YAML driver
                'driver' => array(
                        
                        'MyAuthYamlDriver' => array(
                                'class' => 'Doctrine\ORM\Mapping\Driver\YamlDriver',
                                'cache' => 'array',
                                'extension' => '.dcm.yml',
                                'paths' => [__DIR__ . '/yaml'
                                
                                ]
                        ),
                        'orm_default' => array(
                                'drivers' => array(
                                        __NAMESPACE__. '\Entity' => 'MyAuthYamlDriver',
                                )
                        )
                )
        ] ,

I just added the Yaml driver integration along with the rest of the configuration, I’vn’t removed the migrations configuration in case I need it.

NOTE : fill in the details of your module directory to load the right file location (ie : __DIR__ . ‘/yaml’).

Next we will generate the entity and table from the Yaml schema file.

Yaml & Mysql schema

Usually you will generate a table using the Mysql language, check out the following example :

CREATE TABLE `country` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`country_name` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`country_code` varchar(3) COLLATE utf8_unicode_ci DEFAULT NOT NULL,

PRIMARY KEY (`id`),
UNIQUE KEY `country_index` (`country_name`),

) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Let’s see how we implement this table and its entity in a Yaml file.

MyAuth\Entity\Country:
  type: entity
  table: country
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    country_name:
      type: string
      length: 150
      unique: true
      notnull: true
    country_code:
      type: string
      length: 3
      notnull: true
      unique: true

For more information about the naming conventions of Yaml, follow this link.

Yaml and Doctrine command line

Now it’s time to generate the files using the command line, first the entity :

$ php vendor/bin/doctrine-module orm:generate-entities module/YourModule/src

Doctrine Generate entities

If you receive an error then your location is not properly set. Make sure you also launch the command from the root of your project (hint : check for your vendor directory).

Now check what’s inside the following folder :

/YourModule/src/Entity/

WHAT A SURPRISE !

A brand new Country.php file with all getters and setters and even the Doctrine annotations :

<?php

namespace MyAuth\Entity;

/**
 * Country
 */
class Country
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $country_name;

    /**
     * @var string
     */
    private $country_code;


    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set countryName
     *
     * @param string $countryName
     *
     * @return Country
     */
    public function setCountryName($countryName)
    {
        $this->country_name = $countryName;

        return $this;
    }

    /**
     * Get countryName
     *
     * @return string
     */
    public function getCountryName()
    {
        return $this->country_name;
    }

    /**
     * Set countryCode
     *
     * @param string $countryCode
     *
     * @return Country
     */
    public function setCountryCode($countryCode)
    {
        $this->country_code = $countryCode;

        return $this;
    }

    /**
     * Get countryCode
     *
     * @return string
     */
    public function getCountryCode()
    {
        return $this->country_code;
    }
}

If the above file is not at the right place, then move it to YourModule/src/Entity/ and when you launch the following command :

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

You should get this result :

Doctrine Validate Schema

Error message : Database Fail – The database schema is not in sync with the current mapping files

This is good as it tells you that the database does match the entity schema, so we need to update the tables accordingly and to do so, issue the following :

$ php vendor/bin/doctrine-module orm:schema-tool:update

Doctrine Schema Update tool

Just follow the warning message and everything will go fine, you either update the database manually using the dump sql statement(s) or force the update right from this command :

$ php vendor/bin/doctrine-module orm:schema-tool:update –force

Doctrine Force Update schema

Check your database, you should have a new table inside with the following details :

New Table from Doctrine Entity

Now you are ready to update your code to work with your new entity, the country table here will be used inside a component on its own we will see next, it will allow us to retrieve the list of countries within a form or whatever page.

In another Yaml tutorial, we will see how we can link tables relationships with the same procedure. We will also cover a way to populate the table from the module itself.

Leave a Reply

Want more information?

Related links will be displayed here in this section for you to pick up another good spot to get more details about Web marketing and Search Engine Optimization. There will be some sites which we selected to ease the work of any webmaster or/and web marketer on the Internet.

%d bloggers like this: