Anda di halaman 1dari 27

Working with databases

Introduction
In order to produce your first application, you need to
know how to communicate with your database.
To communicate with it, the database must be
configured properly for use with your framework.
And before the configuration can be made, you
should know how the frameworks join with database
systems and choose your preferred object-relational
mapping (ORM) solution.

ORM
Object-relational mapping (ORM) is a programming
technique which allows you to map your database
tables into PHP objects.
Although there are plenty of good ORM frameworks
out there, it is definitely useful to learn how to build
at-least one among them .
In case youre not sure what ORM really is, just
think of it as having a PHP object per table in your
database.
If you have a user table, then you would have
a user class which would then allow you to add,
update and delete user data from your table.

The three frameworks provide the following ORM


solutions
1. Symphony : Doctrine as the default ORM plugin.
2. CakePHP : Uses its own integrated ORM solution.
Other ORMs can also be used.
3. Zend Framework : a full ORM third-party framework
can be easily installed. Doctrine is accepted.

Consider an example
What table are we mapping?
For example, we will assume we have a users table in
our database which we want to map into an ORM class.
Lets have a look at what fields our users table has:
id
: int
: primary key
name
: varchar
surname : varchar
email
: varchar

Lets create a PHP class.


To create a class that maps out the database table, we will
need to store the table name as well as the fields. Using
the table data above, we can now set up the following
class:
<?php
class user {
// Table Name
static private $sTableName = "users";
// Fields
public $name = "";
public $surname = "";
public $email = "";
} ?>

This is the most basic form of an ORM class. You


have the table name saved as well as the fields.
So just from this class, we can tell what fields
our users table contains.
here the static keyword is used for the table name as
this should be the same (and stay the same) for every
object created from the user class.
Of course, with these variables alone, this class is
useless. We need to be able to select data from the
database. To do this, we can create a function that will
generate the SQL needed to get the data we need.

Create a function that generates SQL.


Lets call the function get(). In it, we need to generate the SQL to avoid
manually writing any ourselves.
<?php
class user
{
static private $sTableName = "users";
public $name ;
public $surname ;
public $email ;
public function get()
{
$sSQL = "SELECT * FROM " . self::$sTableName;
echo $sSQL;
}
}
?>

In main page the code will be


<?php
$oUser = new user();
$oUser->get();
?>

Similarly if you need to insert data you should create an


insert function in the user class eg: ->

<?php class user


{
static private $sTableName = "users";
public $name ;
public $surname ;
public $email ;
public function get()
{
$sSQL = "SELECT * FROM " . self::$sTableName;
echo $sSQL;
}
public function save()
{
$sSQL = INSERT INTO self::$sTableName (name,surname,email)values($this>name,$this->surname,$this->email)
}
}
?>

In main page the code will be


$oUser = new user();
$oUser ->name = 'John Doe';
$oUser ->surname = 'John Doe';
$oUser ->email= john@gmail.com';
$oUser ->save();

Configuring different Database Engines

All ORMs use PDO as a database abstraction layer


An abstraction layer is a very useful solution that
makes it possible to change a database that an
application is using.
Let's use a simple example to make it clear. Let's say
that you need to develop a small application that will
use MySQL. In pure PHP, the code should look like
this.
<?php
$con=mysql_connect(localhost,wroxuser,wroxp
assword) or die(cannot connect);
mysql_select_db(wroxdb) or die(database doesn't
exist);

$query =mysql_query( SELECT * FROM users);


while($row=mysql_fetch_array($query))
{
// do a lot of things
}
mysql_close($con);
?

You use fragments of this code in many places in your


application. This code may be very important, providing
some crucial features of your application.
Suppose if you need to switch to PostgreSQL because of
a very important reason So you are considering how it
will be done.
A trivial solution would be to change your PHP
functions such as mysql_connect() to equivalents for
PostgreSQL.
This is a very time-consuming process and is only a
theory in web application development; nobody follows
this approach.

you should think about a solution that implements a


database abstraction layer idea. The idea is that you need
only to change the configuration of your application, not
its functions, because the functions are chosen in the
lower layer of your application.
For example : lets look at the database specific
congifuration of your framework

Open Database Connectivity(ODBC)


Open Database Connectivity (ODBC) is an API standard
that provides database management and configuration,
independent of the database engine, operating system, or
programming language.
ODBC act as another layer between an application and the
database.
in order to provide the ODBC driver all the information it
needs to establish a connection to database and contains the
following information.
Name of driver connecting to the database
Data source address
Name of the data source
Username accessing the database
Password for user validation

CAKE PHP
In CakePHP, you configure the database with the
DATABASE_CONFIG class.
CakePHP expects database configuration details to be in
a file at app/Config/database.php.
It has a $default variable, which is an array containing
all necessary information about the default environment.

class DATABASE_CONFIG
{
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'cakephpuser',
'password' => 'c4k3roxx!',
'database' => 'my_cakephp_project');
}
datasource :
The name of the datasource this configuration array is for.
Examples: Database/Mysql, Database/Sqlserver,
Database/Postgres, Database/Sqlite.

Persistent :
Whether or not to use a persistent connection to the
database.
host :
The database servers hostname (or IP address).
login:
The username for the account.
password:
The password for the account.
database:
The name of the database for this connection to use.

Zend Framework:
In Zend Framework you have to choose the specific
driver i.e., Zend_Db.
Zend_Db and its related classes provide a
simple SQL database interface for Zend Framework.
The Zend_Db_Adapter is the basic class that is used to
connect your PHP application to an RDBMS.
resources.db.adapter = PDO_MYSQL
resources.db.params.host = localhost
resources.db.params.username = login
resources.db.params.password = secret
resources.db.params.dbname = dbname

Writing Schemas of object models

Schema : a representation of a plan or theory in the


form of an outline or model.
A database schema is the skeleton structure that
represents the logical view of the entire database.
It defines how the data is organized and how the
relations among them are associated.
Propel:
A different approach to writing a schema is proposed in
Propel.
It is presented in xml

<?xml version=1.0 encoding=UTF-8?>


<database name=user_db defaultIdMethod=native
noXsd=true package=lib.model>
<table name=users phpName=Users>
<column name=id type=integer required=true
primaryKey=true autoIncrement=true />
<column name=surname type=varchar size=255 />
<column name=forename type=varchar size=255 />
<column name=created_at type=timestamp />
</table>
</database>

At the beginning, you declare an XML-specific header.


The next line provides the database name.
The DefaultIdMethod tells you about currently used ID
incrementation methods that are specific for every
database. For example, MySQL uses auto_increment,
and PostgreSQL uses sequences.
The native keyword says that Propel should use
database native methods.
if you don't want your schema to be validated before
generating the model then Set noXsd to true.
Table has two attributes.
name is for the database name, and phpName is the
name that will be used in your PHP code.

Doctrine: (Let's look at an example)


Users:
actAs: { Timestampable: }
columns:
forename: string(30)
lastname: string(30)
/config/doctrine/schema.yml
This is a Doctrine schema. First, it describes a table
named Users with 2 columns that are an array of 30
chars.
By default, Doctrine adds an ID field that is a primary
key.
The second line says Timestampable is an attribute that
adds a created_at column.

A schema in Doctrine is described in the schema.yml file


CAKE PHP :
You use PHP code to declare a schema , eg:
var $user = array(
id => array(type => integer, null => false, default
=> NULL,key => primary) ,
forename => array(type => string, null => false,
default => NULL,length => 25),
surname => array(type => string, null => true,
default => NULL,length => 25),
created => array(type => datetime, null => false,
default =>NULL) );
The variable $user is the name of the table that you want
to operate on

Anda mungkin juga menyukai