Loading...

How to Using Traits in Doctrine Entities

View: 630    Dowload: 0   Comment: 0   Post by: hanhga   Category: Php&mySql   Fields: Other

Since PHP 5.4.0, PHP supports a pretty way to reuse code called “Traits” – a set of methods that you can include within another class in order not to repeat yourself. You can read more about traits in previously published SitePoint posts: here, here and here.

Copy - Flat icon for web and mobile apps

Today, I am going to show you how they can be used with Doctrine ORM in a Symfony Environment.

Trait Basics

<?php
trait ExampleTrait {
    public function sayHello() {
        echo "Hello";
    }
}

class A {
    use ExampleTrait;
}

class B {
    use ExampleTrait;
}

$one = new A();
$one->sayHello();    /* return `Hello` */

$two = new B();
$two->sayHello();    /* return `Hello`, too */

As we can see, a basic method sayHello() is declared inside a Trait that is implemented by both A andB classes with a use statement. Easy, right? This example is really short but it should give you the basic knowledge to work with Traits.

 

When it comes to organizing one’s database architecture, it is not uncommon to face code duplication. As an example, suppose we have to develop the usual blog application. At some point, it is likely that we are going to create a basic Article entity and probably a Comment entity as well.

Both entities would benefit from having created_at and updated_at fields (so we can sort results on those columns later). But before digging into traits, let’s see how we could build those entities in Doctrine without them.

Step 1: create the entities

Article entity :

<?php
namespace Blog\AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="article")
 * @ORM\Entity(repositoryClass="Blog\AppBundle\Entity\ArticleRepository")
 */
class Article
{
    /**
     * @ORM\Column(name="idArticle" type="integer")
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /* Other properties you need in your entity: $title, $content, $author...  */

    /** @ORM\Column(name="created_at" type="datetime") */
    private $createdAt;

    /** @ORM\Column(name="updated_at" type="datetime") */
    private $updatedAt;

   /* Getters & Setters */
}

Comment entity :

<?php
namespace Blog\AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="comment")
 * @ORM\Entity(repositoryClass="Blog\AppBundle\Entity\CommentRepository")
 */
class Comment
{
    /**
     * @ORM\Column(name="idComment" type="integer")
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /* Other properties you need in your entity */

    /** @ORM\Column(name="created_at" type="datetime") */
    private $createdAt;

    /** @ORM\Column(name="updated_at" type="datetime") */
    private $updatedAt;

    /* Getters & Setters */
}

The same properties $createdAt and $updatedAt are included in both classes. This is far from DRY. Would Traits be able to help us clean this code up?

Step 2: create the Trait

<?php
// src/Blog/AppBundle/Entity/Traits/TimestampableTrait.php

namespace Blog\AppBundle\Entity\Traits;

use Doctrine\ORM\Mapping as ORM;

trait TimestampableTrait
{
    /**
     * @var datetime $createdAt
     *
     * @ORM\Column(name="created_at", type="datetime")
     */
    private $createdAt;

    /**
     * @var datetime $updatedAt
     *
     * @ORM\Column(name="updated_at", type="datetime")
     */
    private $updatedAt;


    /**
     * Get createdAt
     *
     * @return datetime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set createdAt
     *
     * @param datetime $createdAt
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return datetime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set updatedAt
     *
     * @param datetime $updatedAt
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }
}

Here is a pretty trait file into which we have moved the initial duplicated code. Both $createdAt and$updatedAt as well as all the associated methods are now separated from the entities. As a result, it will be much easier to use them somewhere else. Remember the introduction section with the keyword use.

Step 3: refactor the entities

Article entity :

<?php
// src/Blog/AppBundle/Entity/Article.php

namespace Blog\AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Blog\AppBundle\Entity\Traits\TimestampableTrait;

class Article
{
    use TimestampableTrait;

    /**
     * @ORM\Column(name="idArticle" type="integer")
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /* Other properties you need in your entity */

    /* Getters & Setters */
}

Comment entity :

<?php
// src/Blog/AppBundle/Entity/Comment.php

namespace Blog\AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Blog\AppBundle\Entity\Traits\TimestampableTrait;

/**
 * @ORM\Table(name="comment")
 * @ORM\Entity(repositoryClass="Blog\AppBundle\Entity\CommentRepository")
 */
class Comment
{
    use TimestampableTrait;

    /**
     * @ORM\Column(name="idComment" type="integer")
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /* Other properties you need in your entity */

    /* Getters & Setters */
}

Done! Let’s play with the command line. First, let’s create the entities in our database:

php app/console doctrine:schema:create

This command would yield:

`Article Entity`
 
 | idArticle | *All our other fields...* | created_at | updated_at |
 |-----------|---------------------------|------------|------------|
 
 `Comment Entity`
 
 | idComment | *All our other fields...* | created_at | updated_at |
 |-----------|---------------------------|------------|------------|

Now, if you want to create new objects from these classes, you would find that they both have the common methods available:

<?php
    $article = new Article();
    $article->setUpdatedAt(new \Datetime('now'));

    $comment = new Comment();
    $comment->setUpdatedAt(new \Datetime('now'));
?>

Obviously, we are now ready to persist the data.

Going further

Currently, in the Symfony sphere, many bundles and extensions tend to stick to this way of doing things. The DoctrineBehaviors library from KNPLabs provides a great collection of Traits for entities and repositories. In the same state of mind, I recommend you have an in-depth look at the well known DoctrineExtensions bundle and especially everything about the Timestampable behavior extension.

 

 

How to Using Traits in Doctrine Entities

Since PHP 5.4.0, PHP supports a pretty way to reuse code called “Traits” – a set of methods that you can include within another class in order not to repeat yourself.

Posted on 18-03-2016 

Comment:

To comment you must be logged in members.

Files with category

  • Twitter-like Hashtag Function in PHP

    Twitter-like Hashtag Function in PHP

    View: 215    Download: 1   Comment: 0

    Category: Php&mySql     Fields: none

    If you ever want a function to hashtag and style words within a string which has '#' next to it like twitter. This piece of code will help

  • PSITS Automated Voting System

    PSITS Automated Voting System

    View: 233    Download: 12   Comment: 0

    Category: Php&mySql     Fields: none

    A free sourcecode for PSITS Automated Voting System develop in PHP programming language. The purposed of the system is to automate the process of voting and maintain the quality of data

  • PHP-University Application System

    PHP-University Application System

    View: 206    Download: 13   Comment: 0

    Category: Php&mySql     Fields: none

    Greeting from Malawi the warm heart of Africa. I developed this university registration system project just to share with the people who can make use of the project like this and at the same time for others like students who can learn from it. This...

  • School Event Management System in PHP/MSQLi

    School Event Management System in PHP/MSQLi

    View: 392    Download: 0   Comment: 2

    Category: Php&mySql     Fields: none

    This School Event Management System can create school events such as Volleyball games, Basketball, Cultural presentation, Election of school officers etc . During school election Instead of having a compile list of candidates and voters this system...

  • Resort Reservation System with PayPal/Credit Card/Debit Card Payment

    Resort Reservation System with PayPal/Credit Card/Debit Card Payment

    View: 186    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    This reservation system has the ability to help its customers find available rooms, cottages and even function hall for their convenience . And in here, they will also have the idea of the room rates where they can quickly reserve for their family...

  • Activity log

    Activity log

    View: 190    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    Simple program to track user's activity log-in time and online/offline status.

  • Electricks - eCommerce

    Electricks - eCommerce

    View: 178    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    Electricks is an e-commerce website built using PHP, Bootstrap and some jQuery plugins. It has all the major functionalities of a typical e-shop. This project was used to present in Southern Luzon State University - Lucban. Feel free to use this code...

  • Simple Email App Using PHP

    Simple Email App Using PHP

    View: 156    Download: 1   Comment: 0

    Category: Php&mySql     Fields: none

    Creating a simple PHP script using mail function for sending out emails.

 
File suggestion for you
Loading...
File top downloads
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd