Entities – the Model layer symfony

Entities – the Model layer

Finally, we need to dive into the Model layer of Symfony2 framework. Symfony2 heavily relies on Doctrine2. Doctrine2 is one of the most popular object-relational mapping libraries. While there are alternatives like Propel, in many cases most of the third-party bundles support only Doctrine2.

To create a database model, we need to properly connect to the database first. Make sure that the properties.yml file contains the correct values, and you are able to connect to your database.

Note

Note that in the production mode, each change within the YAML file requires the cache to be cleared, otherwise, it will not be noticed. In the development mode, the configuration is recreated without this requirement.

Now, we need to create our first entity file. In case of entities, we will use annotation as this seems the easiest way to handle database changes and migrations. This will also make it easier for us to make changes in the future and add other stuff related to entity-like validation or file handlers.

Now we will create files to hold tags and tasks for our to-do app. We will start with tags. Create a new file in the src/AppBundle/Entity directory (create one if it does not exist) called Tag.php, and fill it with the following code:

<?php

namespace AppBundleEntity;

use DoctrineORMMapping as ORM;

/**
 * @ORMEntity
 * @ORMTable(name="todo_tag")
 */
class Tag
{
    /**
     * @ORMId
     * @ORMColumn(type="integer")
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $name;
}

You don’t need to generate getters and setters; Symfony2 offers a command-line generator for this. We will use this later in the chapter. To make an entity, we need to let Symfony2 and Doctrine know that we have an entity. To make this possible, we are importing the Doctrine annotation as follows:

use DoctrineORMMapping as ORM;

Now we mark the class as an entity using the @ORMEntity reference. The @ORMTable reference allows us to define the table name, but also sets up the column indexes and unique indexes. Before adding the variables, we are adding the annotation to define their database type and properties:

    /**
     * @ORMId
     * @ORMColumn(type="integer")
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;

The preceding code defines the required primary key and integer. Values will be generated automatically using database engine options (in case of MySQL, it’s auto-increment).

Recommended :  step by step tutorial for using laravel elixir

The property is as follows:

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $name;

This defines the name column and the type of string (string type will be translated to varchar) of length=255. This is also a required value.

Now let’s focus on creating a task entity:

<?php

namespace AppBundleEntity;

use DoctrineORMMapping as ORM;

/**
 * @ORMEntity
 * @ORMTable(name="todo_task")
 */
class Task
{
    /**
     * @ORMId
     * @ORMColumn(type="integer")
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORMManyToMany(targetEntity="Tag")
     */
    private $tags;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $name;

    /**
     * @ORMColumn(type="text", nullable=true)
     */
    private $notes;

    /**
     * @ORMColumn(type="date", nullable=true)
     */
    private $due_date;

    /**
     * @ORMColumn(type="datetime")
     */
    private $created_at;
}

This is similar to the previous one — it contains all the @ORMEntity, @ORMTable, and other annotations. The new one here is an annotation for the text type, date, and the datetime type (this will be translated into the PHP DateTime class). Note that the due_date column is optional, as it does allow null values.

Recommended :  Generate CRUD directly via command line in laravel

The last and interesting thing here is the definition of the relation:

    /**
     * @ORMManyToMany(targetEntity="Tag")
     */
    private $tags;

This will create an M:N relationship between the tags and tasks, allowing the tasks to have multiple tags. There are also other kind of relations—ManyToOne, OneToMany, and OneToOne, to reflect N:1, 1:N, and 1:1 relations. You can read about them in the official Doctrine documentation under http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html.

After we have created these values, we should validate them. Type the following:

$ php app/console doctrine:schema:validate

The result should be similar to the following:

[Mapping]  OK - The mapping files are correct.
[Database] FAIL - The database schema is not in sync with the current mapping file.

While it will show that the database is not yet synced, the mapping should be correct. Note that the properties created within our class have a private status. It’s intentional, we should avoid creating public variables within an entity, and we should keep entities as simple as possible.

Recommended :  Learn How to use Form Builder in laravel From Scratch

Now we should generate the getters/setters. Type the following command:

$ php app/console doctrine:generate:entities --no-backup AppBundle

You should see something similar to the following:

Generating entities for bundle "AppBundle"
  > generating AppBundleEntityTag
  > generating AppBundleEntityTask

If you look at your entities again, you will notice that they contain getters and setters now.

Note

The generator will not override your code, so it’s usually safe to use the no-backup option. If you are uncertain, you can skip it and use the default backup behavior. The generator will then back up your entities before altering them and save them, with the ~ suffix, in the same location where the original files are.

To generate the SQL code, type the following:

$ php app/console doctrine:schema:update --dump-sql

You should see the SQL definitions for the tables we just created:

$ php app/console doctrine:schema:update --force

This will result in the following database update:

Updating database schema...
Database schema updated successfully! "5" queries were executed

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

  • Art Hundiak

    properties.yml file?

Pin It on Pinterest

Shares