Loading Please wait...

Object Relation Maping

An ORM Class is a Database abstraction Layer that isolets SQL Queries by writting/generating it on the fly, with a set of easy and user-friendly methods for full CRUD(Create, read, update, delete) Operation that are linked through Models with the controller(action Logic)

ORM Classes need not to be written from scratch.they are automatically generated by reading ORM Maps. ORM Maps are textual, Highly Human readable configuration files that Manages different tables and links a connection against them.
Zigmoyd Parses those ORM Maps (Configuration Files) and generates the ORM Classes. Although the ORM Classes are auto generated, they <s>can be</s> meant to be edited if required.to handle Custom access methods, adding triggers etc.....

ORM Maps

ORM Maps are stored into etc/conf.d Directory with orm.map.php extension

Although ORM Maps are textual, Human readable configuration Files you dont need to bother about writting a configuration file from scratch. zigmoyd have Command line tools for that automatically too. However its worth to know the structure of that file cause without knowing that you cant edit that file maually.

This is an example ORM Map. where I am mapping two Tables std with alias name Student and std_score with alias Name Marks. and std Table have a Column called syd_name which I'll use with an alias name Name and std_id column is auto Incremented so Its readonly. and you can see how the validation Filters are applied. and these two shares same Connection attribute dataConn (dicsussed in the next section). Zigmoyd commander is capable to generates these coiguration files by itself even with the filters and Error messages.

connection as schoolConn{
}
table std as Student{
    readonly std_id as Id{
    }
    writable std_name as Name{
        required:       Student's Name Must not be left Blank
        string:         Student's Name Must be a String
    }
}
table std_score as Marks{
    readonly id as Id{
    }
    writable student_id as StudentId{
        required:    StudentId Must not be left Blank
        int:         StudentId Must be an Integer
    }
    writable subject as Sub{
        required:       Subject Must not be left Blank
        string:         Subject Name must be a valid string
    }
    writable marks as Marks{
        optional:       __NULL__
        default:        0
        int:            Marks Obtained by the Student Must be an Integer
    }
}
Zigmoyd has the ability to read your database and generate the ORM Maps. however it can be edited and tuned for better experience.

Connection Block

Here we are specifying that we will use a connection file(a simple INI file) called schoolConn.con.ini.php which holds the connection Details
connection as schoolConn{
}

Table Block

A table block holds details about a table. You can have one or more table Blocks that share common connection attributes in one ORM Map.
table admin as Admin{
  readonly id as Id{
  }
  writable usr as User{
    required:       Column `usr` on Table `admin` Must not be left Blank
    string:       Column `usr` on Table `admin` Must be a String
  }
  writable psw as Password{
    required:       Column `psw` on Table `admin` Must not be left Blank
    string:       Column `psw` on Table `admin` Must be a String
  }
  writable sign as Signature{
    optional:       __NULL__
    __default:        New User
    string:       Column `psw` on Table `admin` Must be a String
  }
}
You can give an alias name to a table/column so that you dont need to even remember the original name of that table. all the works will be done through the alias Name you have choosen. just like here we have used column psw with the alias name Password.

you can mark a Column as readonly or writable. (e.g. auto incremented columns can be kept as readonly as you never write any data on those columns cause they are written automatically). just like here we did with id column.

You can set a default value that will be used that will be used if that field is left blank.

You can set Validation Rules and their corresponding error messages That will be checked for validation before writting anything on that column which will auto filter the data whenever you try to write something. which leads to no no unexpected value in the database even if you forget form validation at submitting time.

See also:
Validating ORM

ORM Classes

Zigmoyd parses ORM Maps and generates ORM Classes. Each table has two Classes. these ORM Classes are stored into files called ormMapName.orm.php in apps/model/orm directory in your Project's Directory.and one file is created per ORM Map basis.

so if the above mentioned ORM Map's name is studentOrm.orm.map.php ORM Classes for this Map will be created in a file Called studentOrm.orm.php which will be stored in projects/home/apps/model/orm Directory. and now the question is what will they contain.

In studentOrm.orm.php there will be two Classes.

In the Student Class declearation the Pre Parsed serialized ORM Map will be stored in a member variable called __struct the Student Class represent's student Table where as the StudentRowSet Class represent's the RowSet Object.

Assume there is an ORM Map Like the following (N.B. My Project name is home).

connection as homeConn{
}
table admin as Admin{
  readonly id as Id{
  }
  writable usr as User{
    required:       Column `usr` on Table `admin` Must not be left Blank
    string:       Column `usr` on Table `admin` Must be a String
  }
  writable psw as Password{
    required:       Column `psw` on Table `admin` Must not be left Blank
    string:       Column `psw` on Table `admin` Must be a String
  }
}
and this is the ORM Map generated by reading this.
<?php
//{Generating the List of Classes in this file
$__zigOrmLoadedClassList[] = 'Admin';
//}
?>
<?php
 // This File is auto generated By Zigmoyd ORM Handler by reading the ORM Map on File
 // /media/SRV/zman/projects/home/etc/conf.d/AdminOrm.orm.map.php


if(!class_exists('Admin'))://{ Writting Class Admin for Table admin
class Admin extends manualOrmTable{// Class manualOrmTable ultimately inherits zOrm_inc Class
  var $connAlias = 'manualConn';//Connection Alias name
  var $realTableName = 'admin';//Real Table Name
  var $__struct = 'I7fX19fQ........';//Writting the serialized easy to parse Structure of the ORM Map.

  function Admin(){
    //Writting The Constructor Method
    if(function_exists('overload'))overload(get_class($this));
    $this->__struct = unserialize(base64_decode($this->__struct));
    $this->init();
  }
}
//}
endif;
if(!class_exists('AdminRowSet')):
class AdminRowSet extends manualOrmRowSet{// class manualOrmRowSet ultimately inherits from zigRowSet class
  //you can write your own custom Access Methods methods here

  function AdminRowSet(){
    if(function_exists('overload'))overload(get_class($this));
  }
}
endif;
?>

ORM table level Classes

This is a table level Class. Generated for admin Table.
class Admin extends homeOrmTable{
  var $connAlias = 'schoolConn';//Connection Alias name
  var $realTableName = 'admin';//Real Table Name
  var $__struct = 'Tzo4OiZyI7fX19fQ........';//Writting serialized Structure of preparsed ORM Map

  function Admin(){
    //Writting The Constructor Method
    if(function_exists('overload'))overload(get_class($this));
    $this->__struct = unserialize(base64_decode($this->__struct));
    $this->init();
  }
}
Latter this ORM Class is attached to your Controller through a model.and one instance of this Class is created in $this->db in Controller. and while attaching zigmoyd does something liek $this->db->Admin = new Admin(). Here the Admin Class represents the Admin Table.

ORM RowSet Classes

and when you execute some select query that results more than one Column, the RowSet Class of this table is used as a container of those results.
class AdminRowSet extends homeOrmRowSet{
  //you can write your own custom Access Methods methods here

  function AdminRowSet(){
    if(function_exists('overload'))overload(get_class($this));
  }
}
Just like the table Class a RowSet Class also extends the project level RowSet Class.
ORMMagic.png

Table Level Access method

after attaching the ORM with the Controller you can use various access methods $this->db->Admin to access the data of Admin Table. e.g. You can execute $this->db->Admin->findNameById(1) will write similer to select name frrom admin where id = 1 the above operation will return you a string data representing the name returned, remember it will not return a rowset if only one column is fetched for the shake of simplicity.

On your Controller $this->db acts as an container of all tabe level Objects which

as the ORM Class ultimately inherits zOrm_inc Class You can use all methods of that class and its parent classes. therre are magic methods on zOrm_magic Class. non-magic methods on zOrm_nomagic class and some other base methods too.

Magic Methods.

Magic methods are provided by zOrm_magic Class.
with magic methods you can execute $this->db->Student->findNameById(1) to get the Name of the student who's id is 1. You can execute $this->db->Student->findNameByIdGreaterThan(1) find an array of strings holding names of students who's id is greater than 1. you can also execute $this->db->Student->findName() to get an array of strings All Names e.g. you can execute $this->db->Student->findColBySearch(value) or $this->db->Student->findColBySearchOp(value) or $this->db->Student->findCol()
Col should be replaced by their Column names.
Op Stands for Operator
Equals              =
NotEquals           !=
GreaterThan         >
GreaterThanEquals   >=
LessThan            <
LessThanEquals      <=
Like                LIKE
You can take a look at the zOrm_magic Class to see all magic methods like identifyByCol() or identifyByColOp() or zOrm_magic::setCol() etc..

You can also use findAllById(1) which returns row(s) who's id Is/are 1 or findAllByIdGreaterThan(1) which returns an array of RowSet Objects or findAll() which returns al rows.

find methods are easy to use and enough powerful while fetching values of one or all column and using only one where query. But if you need a custom fetch e.g. fetch just two columns with multiple Where Quiries. at that time you need to use fetch Methods. like fetchCol() or fetchColAsAlias() if you want to select two columns use fetchCol1() and fetchCol2() so that both Col1 and Col2 will be flagged as to be selected.
You need to execute zOrm_base::export() after you do all fetch()s. $this->db->Admin->fetchName() marks that Name column will be selected.$this->db->Admin->fetchNameAsUser() marks that Name column will be selected, But in the ResultSet the Name Column will be Named as User.

identifyBy methods are meant to be used with fetch methods to set where Clauses.you can set as many where Caluses as you wish identifyByCol(value) : $this->db->Admin->identifyById(1) set's an where clause id equals 1
fetchColAsAlias(aliasName) : $this->db->Admin->fetchNameAsUser() marks that Name column will be selected, But in the ResultSet the Name Column will be Named as User.

with set Methods you can set values to the fields for inserting or udating. setCol(Value) set a Column's Value. to be updated/inserted

non-magic methods

all the above mentioned magic methods are a lot usefull however it requires you have overload() enabled or available on your PHP Installation which is installed in most of the cases but still as a very rare case its not installed you can not use magic methods. then you can use equivalent non-magic methods provided by zOrm_noMagic Class.

Common methods

There are a lot of common operations that you need to do which is provided mostly by zOrm_base and zOrm_core class.

insert()
Inserts data into the fields that has been set using setCol() magic method or any other non-magic method to set that field.

remove()
Removes that Specific Row. '''Remember:''' You must use identifyBy() method to identify that Row pirtuularly, else all rows might get deleted.

update()
Update the Specific Row. '''Remember:''' You must use identifyBy() method to identify that Row pirtuularly, else all rows might get updated.

delete()
Same as remove() just a Different Name.

export()
a Select Query by selecting the fields fetch()ed

limit()
Pass a Limit query in it.

group_by()
Pass a group by Query in it.

having()
Pass a having query in it.

order()
Pass an order Query in it.

distinct()
manage the distinct Flag. e.g. If its set to true the select query will be distinct else not.

index()
if your export() returns an array by default they are numarically serially Indexed. However if you pass an Index Column it will be indexed with corresponding values from that field, e.g. index('Id') sometimes seems to be very usefull cause you get the corresponding Ids as array index

Row level Access methods

When your query returns more than one Column's data the output is embedded into a RowSet Object. However when you use export() method result is always embedded into RowSet Object even if there is only one Row in the output.

and when a Rowlevel Object is used you get some more control on that Row set. getCol() You can execute getName() Method if there is a Column called Name in the RowSet Object.

also you can do Row level save(update) or delete operation(s) which will be discussed on another page.

See also:
See Advanced Usage or ORM Layer for Row level operations, custom methods and triggers

Generated on Mon Oct 27 23:51:59 2008 for zigmoyd.kdevelop by doxygen 1.5.6