Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
109 lines (85 sloc) 2.71 KB
title subTitle currentMenu
Doctrine
PHP Best practices
php-orm-doctrine

Persist entity only when you need to

Beginner ###Rule

You have to persist an entity when you want it to be managed by Doctrine. But please don't persist entities that are already managed by Doctrine.

###Explanation

What you should NOT do:
<?php
$article = $entityManager->find('CMS\Article', 1234);
$article->setHeadline('Hello World dude!');
$entityManager->persist($article);
$entityManager->flush();

When you get an entity from the database, it's already managed by Doctrine. You don't have to persist it again. It will not create any errors or bugs but you will add useless code in your project.

Only persist new entity:
<?php
$user = new User;
$user->setName('Mr.Right');
$em->persist($user);
$em->flush();

Naming strategy

Beginner

Rule

Naming strategy can provide rules for automatically generating database identifiers, columns and tables names when the table/column name is not given. This feature helps reduce the verbosity of the mapping document, eliminating repetitive noise

Explanation

What you should NOT do:
/**
 * @Entity
 * @Table(name="users")
 *
 */
class User
{
    /**
     * @Id @GeneratedValue @Column(name="id", type="integer")
     */
    private $id = null;

    /**
     * @Column(name="login", type="string")
     */
    public $login;

    /**
     * @Column(name="password", type="string")
     */
    public $password = null;
}

See in all the annotation we have a name property. Every developper use different naming conventions for columns and tables names.

So your code should look like this:
/**
 * @Entity
 * @Table
 *
 */
class User
{
    /**
     * @Id @GeneratedValue @Column(type="integer")
     */
    private $id = null;

    /**
     * @Column(type="string")
     */
    public $login;

    /**
     * @Column(type="string")
     */
    public $password = null;

With the above code, the developper will not have to take care about the name of columns and tables names, so they will be more efficient and will not have to care about creepy things.

Note: Doctrine provides different naming strategies and let you the possibility to implements your own ones, see Doctrine Naming strategies