Onur Özgür ÖZKAN

Php, Ruby, Kebab, Git Geek

Understanding Doctrine Record State and Kebab_Validate_DoctrineTable

In this tutorial, i try to show you how Kebab_Validate_DoctrineTable manages the unique validation. Lets give an example of unique validation.

Our user.yml

1
2
3
4
5
6
7
8
9
10
11
12
User:
  tableName: system_user
  columns:
    userName:
      type: string(55)
      unique: true
    email:
      type: string(255)
      unique: true
      notnull: true
    password:
      type: string(255)

As you see userName and email fields are unique. So lets continue the example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
class IndexController extends Kebab_Controller_Action
{
    /**
     * Front-end area index action
     * @return void
     */
    public function indexAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        // This is a new user from sign up form
        $newUser = new Model_Entity_User();
        $newUser->email = 'admin@kebab-project.com';

        // This user is exist already on db with the same email address
        $existUser = Doctrine_Core::getTable('Model_Entity_User')->find(2);
        $exitsUser->email = 'admin@kebab-project.com';

        $validate = new Kebab_Validate_DoctrineTable($newUser);
        if ($validate->isValid()) {
            echo 'New user is valid.';
        } else {
            Zend_Debug::dump($validate->getErrors());
        }

        $validateExist = new Kebab_Validate_DoctrineTable($newUser);
        if ($validateExist->isValid()) {
            echo 'Exist user is valid.';
        } else {
            Zend_Debug::dump($validateExist->getErrors());
        }
    }
}
?>

In this example $validate->isValid() === false because there is a user with same email address on db but <$validateExist->isValid() === false because Kebab_Validate_DoctrineTable check the Doctrine_Record is the same with the row on Db. How it is possible? This is not magic, Kebab_Validate_DoctrineTable uses Kebab_Validate_Unique and in isValid method we check the record is not new with this code ! ($state == Doctrine_Record::STATE_TDIRTY || $state == Doctrine_Record::STATE_TCLEAN)

1
2
3
4
5
6
7
8
9
10
11
<?php

// Check primary key if the record is not new
$state = $this->_table->state();
if ( ! ($state == Doctrine_Record::STATE_TDIRTY || $state == Doctrine_Record::STATE_TCLEAN)) {
    foreach ((array) $this->_table->getIdentifierColumnNames() as $pk) {
        if (!is_null($this->_table->$pk)) {
            $query->andWhere("$pk != ?", $this->_table->$pk);
        }
    }
}

Then we get tables identifier columns name with $this->_table->getIdentifierColumnNames() and add an andWhere conditional check the primary key is not equal to data.

This means that you can use Kebab_Validate_DoctrineTable’s unique features when update the records.

Best Regards.