Wednesday, 5 December 2012

PHP OPERATORS

OPERATORS
PHP contains three types of operators: unary operators, binary operators, and
one ternary operator.
Binary operatorsare used on two operands:
2 + 3
14 * 3.1415
$i – 1
These examples are also simple examples of expressions.
PHP can only perform binary operations on two operands that have the
same type. However, if the two operands have different types, PHP automati-cally converts one of them to the other’s type, according to the following rules
(unless stated differently, such as in the concatenation operator).
Booleans, nulls, and resources behave like integers, and they convert in
the following manner:
☞Boolean: False = 0, True= 1
☞Null = 0
☞Resource = The resource’s # (id)
2.6.1 Binary Operators
2.6.1.1 Numeric Operators All the binary operators (except for the concate-
nation operator) work only on numeric operands. If one or both of the oper-
ands are strings, Booleans, nulls, or resources, they are automatically
converted to their numeric equivalents before the calculation is performed
(according to the previous table). 2.6.1.2 Concatenation Operator (.) The concatenation operatorconcate-
nates two strings. This operator works only on strings; thus, any non-string
operand is first converted to one.
The following example would print out "The year is 2000":
$year = 2000;
print "The year is " . $year;
The integer $yearis internally converted to the string "2000"before it is
concatenated with the string’s prefix, "The year is".
2.6.2 Assignment Operators
Assignment operatorsenable you to write a value to a variable. The first
operand (the one on the left of the assignment operator or l value) must be a
variable. The value of an assignment is the final value assigned to the vari-
able; for example, the expression $var = 5has the value 5(and assigns 5to
$var).In addition to the regular assignment operator =, several other assign-ment operators are composites of an operator followed by an equal sign. These
composite operators apply the operator taking the variable on the left as the
first operand and the value on the right (the r value) as the second operand,
and assign the result of the operation to the variable on the left.
For example:
$counter += 2; // This is identical to $counter = $counter + 2;
$offset *= $counter;// This is identical to $offset = $offset *
➥$counter;
The following list show the valid composite assignment operators:
+=, -=, *=, /=, %=, ^=, .=, &=, |=, <<=, >>=
2.6.2.1 By-Reference Assignment Operator PHP enables you to create vari-ables as aliases for other variables. You can achieve this by using the by-reference
assignment operator =&. After a variable aliases another variable, changes to
either one of them affects the other.
For example:
$name = "Judy";
$name_alias =& $name;
$name_alias = "Jonathan";
print $name;
The result of this example is
Jonathan
When returning a variable by-reference from a function (covered later in
this book), you also need to use the assign by-reference operator to assign the
returned variable to a variable:
$retval =& func_that_returns_by_reference();
2.6.3 Comparison Operators
Comparison operatorsenable you to determine the relationship between
two operands.
When both operands are strings, the comparison is performed lexico-graphically. The comparison results in a Boolean value.
For the following comparison operators, automatic type conversions are
performed, if necessary.

For the following two operators, automatic type conversions are notper-formed and, therefore, both the types and the values are compared.
2.6.4 Logical Operators
Logical operatorsfirst convert their operands to boolean values and then
perform the respective comparison.
Operator Name Value
== Equal to Checks for equality
between two arguments
performing type conver-sion when necessary:
1 == "1"results in true
1 == 1results in true
!= Not equal to Inverse of ==.
> Greater than Checks if first operand is
greater than second
< Smaller than Checks if first operand is
smaller than second
>= Greater than or equal to Checks if first operand is
greater or equal to second
<= Smaller than or equal to Checks if first operand
is smaller or equal to
second
Operator Name Value
=== Identical to Same as ==but the types
of the operands have to
match.
No automatic type conver-sions are performed:
1 === "1"results in
false.
1 === 1results in true.
!== Not identical to The inverse of ===.2.6.4 Logical Operators
Logical operatorsfirst convert their operands to boolean values and then
perform the respective comparison. 2.6.4.1 Short-Circuit Evaluation When evaluating the logical and/oropera-tors, you can often know the result without having to evaluate both operands.
For example, when PHP evaluates 0 && 1,it can tell the result will be false by
looking only at the left operand, and it won’t continue to evaluate the right
one. This might not seem useful right now, but later on, we’ll see how we can
use it to execute an operation only if a certain condition is met.
2.6.5 Bitwise Operators
Bitwise operatorsperform an operation on the bitwise representation of
their arguments. Unless the arguments are strings, they are converted to
their corresponding integer representation, and the operation is then per-formed. In case both arguments are strings, the operation is performed
between corresponding character offsets of the two strings (each character is
treated as an integer).

 2.6.6 Unary Operators
Unary operatorsact on one operand.
2.6.7 Negation Operators
Negation operatorsappear before their operand—for example, !$var (!is the
operator, $varis the operand).

2.6.8 Increment/Decrement Operators
Increment/decrement operatorsare unique in the sense that they operate
only on variables and not on any value. The reason for this is that in addition
to calculating the result value, the value of the variable itself changes as well.

As you can see from the previous table, there’s a difference in the value of
post- and pre-increment. However, in both cases, $varis incremented by 1. The
only difference is in the value to which the increment expression evaluates.
Example 1:
$num1 = 5;
$num2 = $num1++;// post-increment, $num2 is assigned $num1's original
➥value
print $num1; // this will print the value of $num1, which is now 6
print $num2; // this will print the value of $num2, which is the
➥original value of $num1, thus, 5Example 2:
$num1 = 5;
$num2 = ++$num1;// pre-increment, $num2 is assigned $num1's
➥incremented value
print $num1; // this will print the value of $num1, which is now 6
print $num2; // this will print the value of $num2, which is the
➥same as the value of $num1, thus, 6
The same rules apply to pre- and post-decrement.
2.6.8.1 Incrementing Strings Strings (when not numeric) are incremented
in a similar way to Perl. If the last letter is alphanumeric, it is incremented by
1. If it was ‘z’, ‘Z’, or ‘9’, it is incremented to ‘a’, ‘A’, or ‘0’ respectively, and the
next alphanumeric is also incremented in the same way. If there is no next
alphanumeric, one is added to the beginning of the string as ‘a’, ‘A’, and ‘1,’
respectively. If this gives you a headache, just try and play around with it.
You’ll get the hang of it pretty quickly.
Note:Non-numeric strings cannot be decremented.
2.6.9 The Cast Operators
PHP provides a C-like way to force a type conversion of a value by using the
cast operators. The operand appears on the right side of the cast operator,
and its result is the converted type according to the following table.
The casting operators change the type of a value and not the type of a
variable. For example:
$str = "5";
$num = (int) $str;
This results in $numbeing assigned the integer value of $str (5), but $str
remains of type string.2.6.10 The Silence Operator
The operator @silences error messages during the evaluation process of an
expression. It is discussed in more detail in Chapter 7.
2.6.11 The One and Only Ternary Operator
One of the most elegant operators is the ?:(question mark) operator. Its for-mat is
truth_expr ? expr1 : expr2
The operator evaluates truth_exprand checks whether it is true. If it is,
the value of the expression evaluates to the value of expr1(expr2is not evalu-ated). If it is false, the value of the expression evaluates to the value of expr2
(expr1is not evaluated).
For example, the following code snippet checks whether $ais set (using
isset()) and displays a message accordingly:
$a = 99;
$message = isset($a) ? '$a is set' : '$a is not set';
print $message;
This example prints the following:
$a is set

Data type of PHP

BASIC DATA TYPES
Eight different data types exist in PHP, five of which are scalar and each of the
remaining three has its own uniqueness. The previously discussed variables
can contain values of any of these data types without explicitly declaring their
type. The variable “behaves” according to the data type it contains.

2.5.1 IntegersIntegersare whole numbers and are equivalent in range as your C compiler’s
longvalue. On many common machines, such as Intel Pentiums, that means a
32-bit signed integer with a range between –2,147,483,648 to +2,147,483,647.
Integers can be written in decimal, hexadecimal (prefixed with 0x), and
octal notation (prefixed with 0), and can include +/-signs.
Some examples of integers include
240000
0xABCD


007
-100
Note:As integers are signed, the right shift operator in PHP always does a
signed shift.
2.5.2 Floating-Point Numbers
Floating-point numbers(also known as real numbers) represent real
numbers and are equivalent to your platform C compiler’s doubledata type.
On common platforms, the data type size is 8 bytes and it has a range of
approximately 2.2E–308 to 1.8E+308. Floating-point numbers include a deci-mal point and can include a +/-sign and an exponent value.
Examples of floating-point numbers include
3.14
+0.9e-2
-170000.5
54.6E42
2.5.3 Strings
Stringsin PHP are a sequence of characters that are always internally null-terminated. However, unlike some other languages, such as C, PHP does not
rely on the terminating null to calculate a string’s length, but remembers its
length internally. This allows for easy handling of binary data in PHP—for
example, creating an image on-the-fly and outputting it to the browser. The
maximum length of strings varies according to the platform and C compiler,
but you can expect it to support at least 2GB. Don’t write programs that test
this limit because you’re likely to first reach your memory limit.
When writing string values in your source code, you can use double
quotes ("), single quotes (') or here-docs to delimit them. Each method is
explained in this section. 2.5.3.1 Double Quotes Examples for double quotes:
"PHP: Hypertext Pre-processor"
"GET / HTTP/1.0\n"
"1234567890"
Strings can contain pretty much all characters. Some characters c
written as is, however, and require special notation:
An additional feature of double-quoted strings is that certain nota
variables and expressions can be embedded directly within them. W
going into specifics, here are some examples of legal strings that embe
ables. The references to variables are automatically replaced with th
ables’ values, and if the values aren’t strings, they are converted t
corresponding string representations (for example, the integer 123wo
first converted to the string "123").
"The result is $result\n"
"The array offset $i contains $arr[$i]"
In cases, where you’d like to concatenate strings with values (such
ables and expressions) and this syntax isn’t sufficient, you can use the .(do
ator to concatenate two or more strings. This operator is covered in a later 

2.5.3.1 Double Quotes Examples for double quotes:
"PHP: Hypertext Pre-processor"
"GET / HTTP/1.0\n"
"1234567890"
Strings can contain pretty much all characters. Some characters can’t be
written as is, however, and require special notation:An additional feature of double-quoted strings is that certain notations of
variables and expressions can be embedded directly within them. Without
going into specifics, here are some examples of legal strings that embed vari-
ables. The references to variables are automatically replaced with the vari-
ables’ values, and if the values aren’t strings, they are converted to their
corresponding string representations (for example, the integer 123would be
first converted to the string "123").
"The result is $result\n"
"The array offset $i contains $arr[$i]"
In cases, where you’d like to concatenate strings with values (such as vari-
ables and expressions) and this syntax isn’t sufficient, you can use the .(dot) oper-
ator to concatenate two or more strings. This operator is covered in a later section.
\n Newline.
\t Tab.
\" Double quote.
\\ Backslash.
\0 ASCII 0 (null).
\r Line feed.
\$ Escape $sign so that it is not treated as a variable but as the
character $.
\{Octal #} The character represented by the specified octal #—for exam-
ple, \70represents the letter 8.
\x{Hexadecimal #} The character represented by the specified hexadecimal #—for
example, \0x32represents the letter 2.

2.5.3.2 Single Quotes In addition to double quotes, single quotes m
delimit strings. However, in contrast to double quotes, single quotes
support all the double quotes’ escaping and variable substitution.
The following table includes the only two escapings supported by
quotes:
Newline.
Tab.
Double quote.
Backslash.
ASCII 0 (null).
Line feed.
Escape $sign so that it is not treated as a variable
character $.
tal #} The character represented by the specified octal #—
ple, \70represents the letter 8.
exadecimal #} The character represented by the specified hexadec
example, \0x32represents the letter 2.
Single quote.
Backslash, used when wanting to represent a back
lowed by a single quote—for example, \\'.Examples:
'Hello, World'
'Today\'s the day'
2.5.3.3 Here-Docs Here-docsenable you to embed large pieces of text in
your scripts, which may include lots of double quotes and single quotes, with-out having to constantly escape them.
The following is an example of a here-doc:
<<PHP stands for "PHP: Hypertext Preprocessor".
The acronym "PHP" is therefore, usually referred to as a recursive acronym
➥because the long form contains the acronym itself.
As this text is being written in a here-doc there is no need to escape the
➥double quotes.
THE_END
The strings starts with <<<, followed by a string that you know doesn’t
appear in your text. It is terminated by writing that string at the beginning of
a line, followed by an optional semicolon (;), and then a required newline (\n).
Escaping and variable substitution in here-docs is identical to double-quoted
strings except that you are not required to escape double quotes.
2.5.3.4 Accessing String Offsets Individual characters in a string can be
accessed using the $str{offset}notation. You can use it to both read and write
string offsets. When reading characters, this notation should be used only to
access valid indices. When modifying characters, you may access offsets that
don’t yet exist. PHP automatically sets that offset to the said character, and if
this results in a gap between the ending of the original string and the offset of
the new character, the gap filled with space characters (' ').
This example creates and prints the string "Andi"(in an awkward way):
$str = "A";
$str{2} = "d";
$str{1} = "n";
$str = $str . "i";
print $str;
Tip: For many cases, PHP has string manipulation functions which use effi-cient algorithms. You should first look at them before you access strings
directly using string offsets. They are usually prefixed with str_. For more
complex needs, the regular expressions functions—most notably the pcre_
family of functions—will come in handyThis support still exists in PHP 5, and you are likely to bump into it often.
However, you should really use the {}notation because it differentiates string
offsets from array offsets and thus, makes your code more readable.
2.5.4 Booleans
Booleans were introduced for the first time in PHP 4 and didn’t exist in prior
versions. A Boolean value can be either trueor false.
As previously mentioned, PHP automatically converts types when
needed. Boolean is probably the type that other types are most often converted
to behind the scenes. This is because, in any conditional code such as if state-ments, loops, and so on, types are converted to this scalar type to check if the
condition is satisfied. Also, comparison operators result in a Boolean value.
Consider the following code fragment:
$numerator = 1;
$denominator = 5;
if ($denominator == 0) {
print "The denominator needs to be a non-zero number\n";
}
The result of the equal-than operator is a Boolean; in this case, it would
be falseand, therefore, the if() statement would not be entered.
Now, consider the next code fragment:
$numerator = 1;
$denominator = 5;
if ($denominator) {
/* Perform calculation */
} else {
print "The denominator needs to be a non-zero number\n";
}
You can see that no comparison operator was used in this example; how-ever, PHP automatically internally converted $denominatoror, to be more accu-rate, the value 5to its Boolean equivalent, true, to perform the if()statement
and, therefore, enter the calculation.
Although not all types have been covered yet, the following table shows
truth values for their values. You can revisit this table to check for the types of
Boolean value equivalents, as you learn about the remaining types.2.5.5 Null
Nullis a data type with only one possible value: the NULLvalue. It marks vari-
ables as being empty, and it’s especially useful to differentiate between the
empty string and null values of databases.
The isset($variable)operator of PHP returns falsefor NULL, and truefor
any other data type, as long as the variable you’re testing exists.
The following is an example of using NULL:
$value = NULL;
2.5.6 Resources
Resources, a special data type, represent a PHP extension resource such as a
database query, an open file, a database connection, and lots of other external
types.
You will never directly touch variables of this type, but will pass them
around to the relevant functions that know how to interact with the specified
resource.
2.5.7 Arrays
An arrayin PHP is a collection of key/value pairs. This means that it maps
keys (or indexes) to values. Array indexescan be either integers or strings
whereas values can be of any type (including other arrays).
Tip:Arrays in PHP are implemented using hash tables, which means that
accessing a value has an average complexity of O(1).
2.5.7.1array()construct Arrays can be declared using the array()lan-
guage construct, which generally takes the following form (elements inside
square brackets, [], are optional):
array([key =>] value, [key =>] value, ...)
Data Type False Values True Values
Integer 0 All non-zero values
Floating point 0.0 All non-zero values
Strings Empty strings ()""
The zero string ()"0"
All other strings
Null Always Never
Array If it does not contain
any elements
If it contains at least
one element
Object Never Always
Resource Never AlwaysThe key is optional, and when it’s not specified, the key is automatically
assigned one more than the largest previous integer key (starting with 0). You
can intermix the use with and without the key even within the same declara-tion.
The value itself can be of any PHP type, including an array. Arrays con-taining arrays give a similar result as multi-dimensional arrays in other lan-guages.
Here are a few examples:
☞array(1, 2, 3)is the same as the more explicit array(0 => 1, 1 => 2, 2
➥=> 3).
☞array("name" => "John", "age" => 28)
☞array(1 => "ONE", "TWO", "THREE")is equivalent to array(1 => "ONE", 2 =>
➥"TWO", 3 => "THREE").
☞array() an empty array.
Here’s an example of a nested array()statement:
array(array("name" => "John", "age" => 28), array("name" =>
➥"Barbara", "age" => 67))
The previous example demonstrates an array with two elements: Each
one is a collection (array) of a person’s information.
2.5.7.2 Accessing Array Elements Array elements can be accessed by using
the $arr[key]notation, where keyis either an integer or string expression.
When using a constant string for key,make sure you don’t forget the single or
double quotes, such as $arr["key"]. This notation can be used for both reading
array elements and modifying or creating new elements.
2.5.7.3 Modifying/Creating Array Elements
$arr1 = array(1, 2, 3);
$arr2[0] = 1;
$arr2[1] = 2;
$arr2[2] = 3;
print_r($arr1);
print_r($arr2);
The print_r()function has not been covered yet in this book, but when it
is passed an array, it prints out the array’s contents in a readable way. You can
use this function when debugging your scripts.
The previous example prints
Array
(
[0] => 1[1] => 2
[2] => 3
)
Array
(
[0] => 1
[1] => 2
[2] => 3
)
So, you can see that you can use both the array()construct and the
$arr[key] notation to create arrays. Usually, array()is used to declare arrays
whose elements are known at compile-time, and the $arr[key]notation is used
when the elements are only computed at runtime.
PHP also supports a special notation, $arr[], where the key is not speci-
fied. When creating new array offsets using this notation (fo example, using it
as the l-value), the key is automatically assigned as one more than the largest
previous integer key.
Therefore, the previous example can be rewritten as follows:
$arr1 = array(1, 2, 3);
$arr2[] = 1;
$arr2[] = 2;
$arr2[] = 3;
The result is the same as in the previous example.
The same holds true for arrays with string keys:
$arr1 = array("name" => "John", "age" => 28);
$arr2["name"] = "John";
$arr2["age"] = 28;
if ($arr1 == $arr2) {
print '$arr1 and $arr2 are the same' . "\n";
}
The message confirming the equality of both arrays is printed.
2.5.7.4 Reading array values You can use the $arr[key]notation to read
array values. The next few examples build on top of the previous example:
print $arr2["name"];
if ($arr2["age"] < 35) {
print " is quite young\n";
}This example prints
John is quite young
Note:As previously mentioned, using the $arr[]syntax is not supported
when reading array indexes, but only when writing them.
2.5.7.5 Accessing Nested Arrays (or Multi-Dimensional Arrays) When
accessing nested arrays, you can just add as many square brackets as required
to reach the relevant value. The following is an example of how you can
declare nested arrays:
$arr = array(1 => array("name" => "John", "age" => 28), array("name"
➥=> "Barbara", "age" => 67))
You could achieve the same result with the following statements:
$arr[1]["name"] = "John";
$arr[1]["age"] = 28;
$arr[2]["name"] = "Barbara";
$arr[2]["age"] = 67;
Reading a nested array value is trivial using the same notation. For
example, if you want to print John’s age, the following statement does the
trick:
print $arr[1]["age"];
2.5.7.6 Traversing Arrays Using foreach There are a few different ways of
iterating over an array. The most elegant way is the foreach()loop construct.
The general syntax of this loop is
foreach($array as [$key =>] [&] $value)
...
$keyis optional, and when specified, it contains the currently iterated
value’s key, which can be either an integer or a string value, depending on the
key’s type.
Specifying &for the value is also optional, and it has to be done if you are
planning to modify $valueand want it to propagate to $array.In most cases,
you won’t want to modify the $valuewhen iterating over an array and will,
therefore, not need to specify it.Here’s a short example of the foreach()loop:
$players = array("John", "Barbara", "Bill", "Nancy");
print "The players are:\n";
foreach ($players as $key => $value) {
print "#$key = $value\n";
}
The output of this example is
The players are:
#0 = John
#1 = Barbara
#2 = Bill
#3 = Nancy
Here’s a more complicated example that iterates over an array of people
and marks which person is considered old and which one is considered young:
$people = array(1 => array("name" => "John", "age" => 28),
➥array("name" => "Barbara", "age" => 67));
foreach ($people as &$person) {
if ($person["age"] >= 35) {
$person["age group"] = "Old";
} else {
$person["age group"] = "Young";
}
}
print_r($people);
Again, this code makes use of the print_r()function.
The output of the previous code is the following:
Array
(
[1] => Array
(
[name] => John
[age] => 28
[age group] => Young
)
[2] => Array
(
[name] => Barbara
[age] => 67
[age group] => Old)
)
You can see that both the John and Barbara arrays inside the $people
array were added an additional value with their respective age group.
2.5.7.7 Traversing Arrays Using list()and each()  Although foreach()
is the nicer way of iterating over an array, an additional way of traversing an
array is by using a combination of the list()construct and the each()func-
tion:
$players = array("John", "Barbara", "Bill", "Nancy");
reset($players);
while (list($key, $val) = each($players)) {
print "#$key = $val\n";
}
The output of this example is
#0 = John
#1 = Barbara
#2 = Bill
#3 = Nancy
2.5.7.8reset() Iteration in PHP is done by using an internal array pointer
that keeps record of the current position of the traversal. Unlike with
foreach(), when you want to use each()to iterate over an array, you must
reset()the array before you start to iterate over it. In general, it is best for
you to always use foreach()and not deal with this subtle nuisance of each()
traversal.
2.5.7.9each() The each()function returns the current key/value pair and
advances the internal pointer to the next element. When it reaches the end
of of the array, it returns a booloean value of false. The key/value pair is
returned as an array with four elements: the elements 0and "key", which
have the value of the key, and elements 1and "value", which have the value
of the value. The reason for duplication is that, if you’re accessing these ele-
ments individually, you’ll probably want to use the names such as
$elem["key"]and $elem["value"]:
$ages = array("John" => 28, "Barbara" => 67);
reset($ages);
$person = each($ages);print $person["key"];
print " is of age ";
print $person["value"];
This prints
John is of age 28
When we explain how the list()construct works, you will understand
why offsets 0 and 1 also exist.
2.5.7.10list() The list()construct is a way of assigning multiple array
offsets to multiple variables in one statement:
list($var1, $var2, ...) = $array;
The first variable in the list is assigned the array value at offset 0, the
second is assigned offset 1, and so on. Therefore, the list()construct trans-lates into the following series of PHP statements:
$var1 = $array[0];
$var2 = $array[1];
...
As previously mentioned, the indexes 0 and 1 returned by each()are
used by the list()construct. You can probably already guess how the combi-nation of list()and each()work.
Consider the highlighted line from the previous $playerstraversal example:
$players = array("John", "Barbara", "Bill", "Nancy");
reset($players);
while (list($key, $val) = each($players)) {
print "#$key = $val\n";
}
What happens in the boldfaced line is that during every loop iteration,
each()returns the current position’s key/value pair array, which, when exam-ined with print_r(), is the following array:
Array
(
[1] => John
[value] => John[0] => 0
[key] => 0
)
Then, the list()construct assigns the array’s offset 0 to $keyand offset 1
to $val.
2.5.7.11 Additional Methods for Traversing Arrays You can use other func-tions to iterate over arrays including current()and next(). You shouldn’t use
them because they are confusing and are legacy functions. In addition, some
standard functions allow all sorts of elegant ways of dealing with arrays such
as array_walk(), which is covered in a later chapter.
2.5.8 Constants
In PHP, you can define names, called constants, for simple values. As the
name implies, you cannot change these constants once they represent a cer-tain value. The names for constants have the same rules as PHP variables
except that they don’t have the leading dollar sign. It is common practice in
many programming languages—including PHP—to use uppercase letters for
constant names, although you don’t have to. If you wish, which we do not rec-ommend, you may define your constants as case-insensitive, thus not requir-ing code to use the correct casing when referring to your constants.
Tip:Only use case-sensitive constants both to be consistent with accepted cod-ing standards and because it is unclear if case-insensitive constants will con-tinued to be supported in future versions of PHP.
Unlike variables, constants, once defined, are globally accessible. You
don’t have to (and can’t) redeclare them in each new function and PHP file.
To define a constant, use the following function:
define("CONSTANT_NAME", value [, case_sensitivity])
Where:
☞"CONSTANT_NAME"is a string.
☞valueis any valid PHP expression excluding arrays and objects.
☞case_sensitivityis a Boolean (true/false) and is optional. The default is
true.
An example for a built-in constant is the Boolean value true, which is
registered as case-insensitive.
Here’s a simple example for defining and using a constant:

PHP veriables

VARIABLES
Variables in PHP are quite different from compiled languages such as C and
Java. This is because their weakly typed nature, which in short means you
don’t need to declare variables before using them, you don’t need to declare
their type and, as a result, a variable can change the type of its value as much
as you want.
Variables in PHP are preceded with a $sign, and similar to most modern
languages, they can start with a letter (A-Za-z) or _(underscore) and can then
contain as many alphanumeric characters and underscores as you like.
Examples of legal variable names include
$count
$_Obj
$A123
Example of illegal variable names include
$123
$*ABC
As previously mentioned, you don’t need to declare variables or their
type before using them in PHP. The following code example uses variables:
$PI = 3.14;
$radius = 5;
$circumference = $PI * 2 * $radius; // Circumference = π* d
You can see that none of the variables are declared before they are used.
Also, the fact that $PIis a floating-point number, and $radius(an integer) is
not declared before they are initialized.
PHP does not support global variables like many other programming
languages (except for some special pre-defined variables, which we discuss
later). Variables are local to their scope, and if created in a function, they are
only available for the lifetime of the function. Variables that are created in
the main script (not within a function) aren’t global variables; you cannot sethem inside functions, but you can access them by using a special array
$GLOBALS[], using the variable’s name as the string offset. The previous
example can be rewritten the following way:
$PI = 3.14;
$radius = 5;
$circumference = $GLOBALS["PI"] * 2 * $GLOBALS["radius"];
➥// Circumference = π* d
You might have realized that even though all this code is in the main
scope (we didn’t make use of functions), you are still free to use $GLOBALS[],
although in this case, it gives you no advantage. 
Indirect References to Variables
An extremely useful feature of PHP is that you can access variables by using
indirect references, or to put it simply, you can create and access variables by
name at runtime.
Consider the following example:
$name = "John";
$$name = "Registered user";
print $John;
This code results in the printing of "Registered user."
The bold line uses an additional $to access the variable with name speci-fied by the value of $name("John") and changing its value to "Registered user".
Therefore, a variable called $Johnis created.
You can use as many levels of indirections as you want by adding addi-tional $signs in front of a variable.
.Managing Variables
Three language constructs are used to manage variables. They enable you to
check if certain variables exist, remove variables, and check variables’ truth
values.
2.4.2.1isset() isset()determines whether a certain variable has already
been declared by PHP. It returns a boolean value trueif the variable has
already been set, and falseotherwise, or if the variable is set to the value NULL.
Consider the following script:
if (isset($first_name)) {
print '$first_name is set';
}
This code snippet checks whether the variable $first_nameis defined. If
$first_nameis defined, isset()returns true, which will display '$first_name is
set.' If it isn’t, no output is generatedthem inside functions, but you can access them by using a special array
$GLOBALS[], using the variable’s name as the string offset. The previous
example can be rewritten the following way:
$PI = 3.14;
$radius = 5;
$circumference = $GLOBALS["PI"] * 2 * $GLOBALS["radius"];
➥// Circumference = π* d
You might have realized that even though all this code is in the main
scope (we didn’t make use of functions), you are still free to use $GLOBALS[],
although in this case, it gives you no advantage.2.4.2.2unset() unset()“undeclares” a previously set variable, and frees
any memory that was used by it if no other variable references its value. A call
to isset() on a variable that has been unset()returns false.
For example:
$name = "John Doe";
unset($name);
if (isset($name)) {
print ’$name is set';
}
This example will not generate any output, because isset()returns
false.
unset()can also be used on array elements and object properties similar
to isset().2.4.2.3empty() empty() may be used to check if a variable has not been
declared or its value is false. This language construct is usually used to check
if a form variable has not been sent or does not contain data. When checking a
variable’s truth value, its value is first converted to a Boolean according to the
rules in the following section, and then it is checked for true/false.
For example:
if (empty($name)) {
print 'Error: Forgot to specify a value for $name';
}
This code prints an error message if $namedoesn’t contain a value that
evaluates to true. 
Superglobals
As a general rule, PHP does not support global variables (variables that can
automatically be accessed from any scope). However, certain special internal
variables behave like global variables similar to other languages. These vari-ables are called superglobalsand are predefined by PHP for you to use. Some
examples of these superglobals are
☞$_GET[]. An array that includes all the GETvariables that PHP received
from the client browser.
☞$_POST[]. An array that includes all the POSTvariables that PHP received
from the client browser.
☞$_COOKIE[]. An array that includes all the cookies that PHP received from
the client browser.
☞$_ENV[]. An array with the environment variables.
☞$_SERVER[]. An array with the values of the web-server variables.
These superglobals and others are detailed in Chapter 5, “How to Write a
Web Application with PHP.” On a language level, it is important to know that
you can access these variables anywhere in your script whether function,
method, or global scope. You don’t have to use the $GLOBALS[]array, which
allows for accessing global variables without having to predeclare them or
using the deprecated globalskeyword.

other Feature in php 5

1.4 OTHER NEW FEATURES IN PHP 5
This section discusses new features introduced in PHP 5.
1.4.1 New Memory Manager
The Zend Engine features a new memory manager. The two main advantages
are better support for multi-threaded environments (allocations do not need to
perform any mutual exclusion locks), and after each request, freeing the allo-cated memory blocks is more efficient. Because this is an underlying infra-structure change, you will not notice it directly as the end user.

1.4.2 Dropped Support for Windows 95
Running PHP on the Windows 95 platform is not supported anymore due to
Windows 95 does not support the functionality that PHP uses. Because
Microsoft officially stopped supporting it in 2002, the PHP development com-munity decided that dropping the support was a wise decision.

GENERALPHP CHANGES in PHP 5

GENERALPHP CHANGES in PHP 5
1.3.1 XML and Web Services

Following the changes in the language, the XML updates in PHP 5 are proba-
bly the most significant and exciting. The enhanced XML functionality in PHP
5 puts it on par with other web technologies in some areas and overtakes them
in others.
1.3.1.1 The Foundation
XML support in PHP 4 was implemented using a
variety of underlying XML libraries. SAX support was implemented using the
old Expat library, XSLT was implemented using the Sablotron library (or using
libxml2 via the DOM extension), and DOM was implemented using the more
powerful libxml2 library by the GNOME project.
Using a variety of libraries did not make PHP 4 excel when it came to
XML support. Maintenance was poor, new XML standards were not always
supported, performance was not as good as it could have been, and interopera-
bility between the various XML extensions did not exist.
In PHP 5, all XML extensions have been rewritten to use the superb
libxml2 XML toolkit (http://www.xmlsoft.org/). It is a feature-rich, highly main-
tained, and efficient implementation of the XML standards that brings cutting-
edge XML technology to PHP.

All the afore-mentioned extensions (SAX, DOM, and XSLT) now use
libxml2, including the new additional extensions SimpleXML and SOAP.
1.3.1.2 SAX As previously mentioned, the new SAX implementation has
switched from using Expat to libxml2. Although the new extension should be
compatible, some small subtle differences might exist. Developers who still
want to work with the Expat library can do so by configuring and building
PHP accordingly (which is not recommended).
1.3.1.3 DOM Although DOM support in PHP 4 was also based on the libxml2
library, it had bugs, memory leaks, and in many cases, the API was not W3C-compliant. The DOM extension went through a thorough facelift for PHP 5. Not
only was the extension mostly rewritten, but now, it is also W3C-compliant. For
example, function names now use studlyCapsas described by the W3C standard,
which makes it easier to read general W3C documentation and implement what
you have learned right away in PHP. In addition, the DOM extension now sup-ports three kinds of schemas for XML validation: DTD, XML schema, and
RelaxNG.
As a result of these changes, PHP 4 code using DOM will not always run
in PHP 5. However, in most cases, adjusting the function names to the new
standard will probably do the trick.
1.3.1.4 XSLT In PHP 4, two extensions supported XSL Transformations: the
Sablotron extension and the XSLT support in the DOM extension. PHP 5 fea-tures a new XSL extension and, as previously mentioned, it is based on the
libxml2 extension. As in PHP 5, the XSL Transformation does not take the
XSLT stylesheet as a parameter, but depends on the DOM extension to load it.
The stylesheet can be cached in memory and may be applied to many docu-ments, which saves execution time.
1.3.1.5 SimpleXML When looking back in a year or two, it will be clear that
SimpleXML revolutionized the way PHP developers work with XML files.
Instead of having to deal with DOM or—even worse—SAX, SimpleXML repre-sents your XML file as a native PHP object. You can read, write, or iterate over
your XML file with ease, accessing elements and attributes.
Consider the following XML file:


John Doe
87234838


Janet Smith
72384329

The following code prints each client’s name and account number:
$clients = simplexml_load_file('clients.xml');
foreach ($clients->client as $client) {
print "$client->name has account number $client
➥>account_number\n";
}
It is obvious how simple SimpleXML really is.
In case you need to implement an advanced technique in your Sim-pleXML object that is not supported in this lightweight extension, you can
convert it to a DOM tree by calling it dom_import_simplexml(), manipulate it in
DOM, and convert it to SimpleXML using simplexml_import_dom().
Thanks to both extensions using the same underlying XML library,
switching between them is now a reality.
1.3.1.6 SOAP PHP 4 lacked official native SOAP support. The most com-monly used SOAP implementation was PEARs, but because it was imple-mented entirely in PHP, it could not perform as well as a built-in C extension.
Other available C extensions never reached stability and wide adoption and,
therefore, were not included in the main PHP 5 distribution.
SOAP support in PHP 5 was completely rewritten as a C extension and,
although it was only completed at a very late stage in the beta process, it was
incorporated into the default distribution because of its thorough implementa-tion of most of the SOAP standard.
The following calls SomeFunction()defined in a WSDL file:
$client = new SoapClient("some.wsdl");
$client->SomeFunction($a, $b, $c);
1.3.1.7 New MySQLi (MySQL Improved) Extension For PHP 5, MySQL AB
(http://www.mysql.com) has written a new MySQL extension that enables you
to take full advantage of the new functionality in MySQL 4.1 and later. As
opposed to the old MySQL extension, the new one gives you both a functional
and an OO interface so that you can choose what you prefer. New features sup-ported by this extension include prepared statements and variable binding,
SSL and compressed connections, transaction control, replication support, and
more.
1.3.1.8 SQLite Extension Support for SQLite (http://www.sqlite.org) was
first introduced in the PHP 4.3.x series. It is an embedded SQL library that
does not require an SQL server, so it is suitable for applications that do not
require the scalability of SQL servers or, if you deploy at an ISP that does notoffer access to an SQL server. Contrary to what its name implies, SQLite has
many features and supports transactions, sub-selects, views, and large data-base files. It is mentioned here as a PHP 5 feature because it was introduced
so late in the PHP 4 series, and because it takes advantage of PHP 5 by pro-viding an OO interface and supporting iterators.
1.3.1.9 Tidy Extension PHP 5 includes support for the useful Tidy (http://
tidy.sf.net/) library. It enables PHP developers to parse, diagnose, clean, and
repair HTML documents. The Tidy extension supports both a functional and
an OO interface, and its API uses the PHP 5 exception mechanism.
1.3.1.10 Perl Extension Although not bundled in the default PHP 5 package,
the Perl extension allows you to call Perl scripts, use Perl objects, and use
other Perl functionality natively from within PHP. This new extension sits
within the PECL (PHP Extension Community Library) repository at http://
pecl.php.net/package/perl.

Features of PHP 5

Language Features
For a more complete example, see Chapter 4, “PHP 5 Advanced OOP and
Design Patterns.”
☞__autoload().
Many developers writing object-oriented applications create one PHP
source file per class definition. One of the biggest annoyances is having to
write a long list of needed inclusions at the beginning of each script (one for
each class). In PHP 5, this is no longer necessary. You may define an
__autoload()function that is automatically called in case you are trying to use
a class that has not been defined yet. By calling this function, the scripting
engine offers one last chance to load the class before PHP bails out with an
error:
function __autoload($class_name) {
include_once($class_name . "php");
}
$obj = new MyClass1();
$obj2 = new MyClass2();
Other New Language Features
☞Exception handling.
PHP 5 adds the ability for the well-known try/throw/catchstructured
exception-handling paradigm. You are only allowed to throw objects that
inherit from the Exceptionclass:
class SQLException extends Exception {
public $problem;
function __construct($problem) {
$this->problem = $problem;
}
}
try {
...
throw new SQLException("Couldn't connect to database");
...
} catch (SQLException $e) {
print "Caught an SQLException with problem $obj->problem";
} catch (Exception $e) {
print "Caught unrecognized exception";
}
Currently for backward-compatibility purposes, most internal functions
do not throw exceptions. However, new extensions make use of this capability,
and you can use it in your own source code. Also, similar to the already exist-ing set_error_handler(), you may use set_exception_handler()to catch an
unhandled exception before the script terminates.
Gutmans_Ch01 Page 7 Thursday, September 23, 2004 2:35 PM
8  What Is New in PHP 5? Chap. 1
☞foreachwith references.
In PHP 4, you could not iterate through an array and modify its values.
PHP 5 supports this by enabling you to mark the foreach()loop with the
&(reference) sign, which makes any values you change affect the array
over which you are iterating:
foreach ($array as &$value) {
if ($value === "NULL") {
$value = NULL;
}
}
☞Default values for by-reference parameters.
In PHP 4, default values could be given only to parameters, which are
passed by-values. PHP 5 now supports giving default values to by-reference parameters:
function my_func(&$arg = null) {
if ($arg === NULL) {
print '$arg is empty';
}
}
my_func();

PHP 5

1  PHP 5

1.1 INTRODUCTION
                 Only time will tell if the PHP 5 release will be as successful as its two prede- cessors (PHP 3 and PHP 4). The new features and changes aim to rid PHP of any weaknesses it may have had and make sure that it stays in the lead as the world’s best web-scripting language. This book details PHP 5 and its new features. However, if you are familiar with PHP 4 and are eager to know what is new in PHP 5, this chapter is for you. When you finish reading this chapter, you will have learned ☞The new language features ☞News concerning PHP extensions ☞Other noteworthy changes to PHP’s latest version  
1.2  LANGUAGE FEATURES 
1.2.1 New Object-Oriented Model 
When Zeev Suraski added the object-oriented syntax back in the days of PHP 3, it was added as “syntactic sugar for accessing collections.” The OO model also had support for inheritance and allowed a class (and object) to aggregate both methods and properties, but not much more. When Zeev and Andi Gut- mans rewrote the scripting engine for PHP 4, it was a completely new engine; it ran much faster, was more stable, and boasted more features. However, the OO model first introduced in PHP 3 was barely touched. Although the object model had serious limitations, it was used exten- sively around the world, often in large PHP applications. This impressive use of the OOP paradigm with PHP 4, despite its weaknesses, led to it being the main focus for the PHP 5 release.So, what were some of the limitations in PHP 3 and 4? The biggest limi-tation (which led to further limitations) was the fact that the copy semantics of
objects were the same as for native types. So, how did this actually affect the
PHP developer? When assigning a variable (that points to an object) to
another variable, a copy of the object would be created. Not only did this
impact performance, but it also usually led to obscure behavior and bugs in
PHP 4 applications because many developers thought that both variables
would point at the same object, which was not the case. The variables were
instead pointing at separate copies of the same object. Changing one would
not change the other.
For example:
class Person {
var $name;
function getName()
{
return $this->name;
}
function setName($name)
{
$this->name = $name;
}
function Person($name)
{
$this->setName($name);
}
}
function changeName($person, $name)
{
$person->setName($name);
}
$person = new Person("Andi");
changeName($person, "Stig");
print $person->getName();
In PHP 4, this code would print out "Andi". The reason is that we pass
the object $personto the changeName()function by-value, and thus, $personis
copied and changeName()works on a copy of $person.
This behavior is not intuitive, as many developers would expect the Java-like behavior. In Java, variables actually hold a handle (or pointer) to the
object, and therefore, when it is copied, only the handle (and not the entire
object) is duplicated.
There were two kinds of users in PHP 4: the ones who were aware of this
problem and the ones who were not. The latter would usually not notice this
problem and their code was written in a way where it did not really matter if
the problem existed. Surely some of these people had sleepless nights trying to
track down weird bugs that they could not pinpoint. The former group dealt
with this problem by always passing and assigning objects by reference. This
would prevent the engine from copying their objects, but it would be a head-ache because the code included numerous & signs.The old object model not only led to the afore-mentioned problems, but
also to fundamental problems that prevented implementing some additional
features on top of the existing object model.
In PHP 5, the infrastructure of the object model was rewritten to work
with object handles. Unless you explicitly clone an object by using the clone
keyword, you never create behind-the-scenes duplicates of your objects. In
PHP 5, you don’t need a need to pass objects by reference or assign them by
reference.
Note:Passing by reference and assigning by reference are still sup-ported, in case you want to actually change a variable’s content (whether
object or other type).
1.2.2 New Object-Oriented Features
The new OO features are too numerous to give a detailed description in this
section. Chapter 3, “PHP 5 OO Language,” details each feature.
The following list provides the main new features:
☞public/private/protectedaccess modifiers for methods and properties.
Allows the use of common OO access modifiers to control access to
methods and properties:
class MyClass {
private $id = 18;
public function getId() {
return $this->id;
}
}
☞Unified constructor name __construct().
Instead of the constructor being the name of the class, it is now declared
as __construct(), which makes it easier to shift classes inside class hier-archies:
class MyClass {
function __construct() {
print "Inside constructor";
}
}
☞Object destructor support by defining a __destructor() method.
Allows defining a destructor function that runs when an object
is destroyed:
class MyClass {
function __destruct() {
print ”Destroying object”;
}
}
Gutmans_Ch01 Page 3 Thursday, September 23, 2004 2:35 PM
4  What Is New in PHP 5? Chap. 1
☞Interfaces.
Gives the ability for a class to fulfill more than one is-a relationships. A class can
inherit only from one class, but may implement as many interfaces as it wants:
interface Display {
function display();
}
class Circle implements Display {
function display() {
print "Displaying circle\n";
}
}
☞instanceofoperator.
Language-level support for is-a relationship checking. The PHP 4 is_a() function
is now deprecated:
if ($obj instanceof Circle) {
print '$obj is a Circle';
}
☞Final methods.
The finalkeyword allows you to mark methods so that an inheriting class cannot overload
them:
class MyClass {
final function getBaseClassName() {
return __CLASS__;
}
}
☞Final classes.
After declaring a class as final, it cannot be inherited. The following example
would error out.
final class FinalClass {
}
class BogusClass extends FinalClass {
}
☞Explicit object cloning.
To clone an object, you must use the clonekeyword. You may declare a __clone()
method, which will be called during the clone process (after the properties have
been copied from the original object):
Gutmans_Ch01 Page 4 Thursday, September 23, 2004 2:35 PM
1.2 Language Features 5
class MyClass {
function __clone() {
print "Object is being cloned";
}
}
$obj = new MyClass();
$obj_copy = clone $obj;
☞Class constants.
Class definitions can now include constant values and are referenced
using the class:
class MyClass {
const SUCCESS = "Success";
const FAILURE = "Failure";
}
print MyClass::SUCCESS;
☞Static methods.
You can now define methods as static by allowing them to be called from
non-object context. Static methods do not define the $thisvariable
because they are not bound to any specific object:
class MyClass {
static function helloWorld() {
print "Hello, world";
}
}
MyClass::helloWorld();
☞Static members.
Class definitions can now include static members (properties) that are
accessible via the class. Common usage of static members is in the
Singleton pattern:
class Singleton {
static private $instance = NULL;
private function __construct() {
}
static public function getInstance() {
if (self::$instance == NULL) {
self::$instance = new Singleton();
}
return self::$instance;
}
}
Gutmans_Ch01 Page 5 Thursday, September 23, 2004 2:35 PM
6  What Is New in PHP 5? Chap. 1
☞Abstract classes.
A class may be declared abstractto prevent it from being instantiated.
However, you may inherit from an abstract class:
abstract class MyBaseClass {
function display() {
print "Default display routine being called";
}
}
☞Abstract methods.
A method may be declared abstract, thereby deferring its definition to an
inheriting class. A class that includes abstract methods must be declared
abstract:
abstract class MyBaseClass {
abstract function display();
}
☞Class type hints.
Function declarations may include class type hints for their parameters.
If the functions are called with an incorrect class type, an error occurs:
function expectsMyClass(MyClass $obj) {
}
☞Support for dereferencing objects that are returned from methods.
In PHP 4, you could not directly dereference objects that were returned
from methods. You had to first assign the object to a dummy variable and
then dereference it.
PHP 4:
$dummy = $obj->method();
$dummy->method2();
PHP 5:
$obj->method()->method2();
☞Iterators.
PHP 5 allows both PHP classes and PHP extension classes to implement
an Iteratorinterface. After you implement this interface, you can iterate
instances of the class by using the foreach()language
construct:
$obj = new MyIteratorImplementation();
foreach ($obj as $value) {
print "$value";
}
Gutmans_Ch01 Page 6 Thursday, September 23, 2004 2:35 PM

Tuesday, 14 August 2012

struts

1. Introduction

    "Read the directions and directly you will be directed in the right direction."

The framework documentation is written for active web developers and assumes a working knowledge about how Java web applications are built. For more about the underlying nuts and bolts, see the Key Technologies Primer.

1.1 Forward into the Past! (or a brief history of Struts)

When Java servlets were first invented, many programmers quickly realized that they were a Good Thing. They were faster and more powerful that standard CGI, portable, and infinitely extensible.

But writing HTML to send to the browser in endless println() statements was tiresome and problematic. The answer to that was JavaServer Pages, which turned Servlet writing inside-out. Now developers could easily mix HTML with Java code, and have all the advantages of servlets. The sky was the limit!

Java web applications quickly became "JSP-centric". This in-and-of itself was not a Bad Thing, but it did little to resolve flow control issues and other problems endemic to web applications.

Clearly, another paradigm was needed ...

Many clever developers realized that JavaServer Pages AND servlets could be used together to deploy web applications. The servlets could help with the control-flow, and the JSPs could focus on the nasty business of writing HTML. In due course, using JSPs and servlets together became known as Model 2 (meaning, presumably, that using JSPs alone was Model 1).

Of course, there is nothing new under the Sun ... and many have been quick to point out that JSP's Model 2 follows the classic Model-View-Controller design pattern abstracted from the venerable Smalltalk MVC framework. Java Web developers now tend to use the terms Model 2 and MVC interchangeably. In this guide, we use the MVC paradigm to describe the framework architecture, which might be best termed a Model 2/MVC design.

The Apache Struts Project was launched in May 2000 by Craig R. McClanahan to provide a standard MVC framework to the Java community. In July 2001, version 1.0 was released, and IOHO, Java Model 2 development has never been quite the same.

1.2 The Model-View-Controller ('MVC') Design Pattern

The term "MVC" originated with the SmallTalk Model-View-Controller framework. Under MVC, an application is seen as having three distinct parts. The problem domain is represented by the Model. The output to the user is represented by the View. And, the input from the user is represented by Controller.

1.2.1 The Model: System State and Business Logic JavaBeans

The Model portion of an MVC-based system can be often be divided into two major subsystems -- the internal state of the system and the actions that can be taken to change that state.

In grammatical terms, we might think about state information as nouns (things) and actions as verbs (changes to the state of those things).

Many applications represent the internal state of the system as a set of one or more JavaBeans. The bean properties represent the details of the system' state. Depending on your application's complexity, these beans may be self contained (and know how to persist their own state), or they may be facades that know how to retrieve the system's state from another component. This component may be a database, a search engine, an Entity Enterprise JavaBean, a LDAP server, or something else entirely.

Large-scale applications will often represent the set of possible business operations as methods that can be called on the bean or beans maintaining the state information. For example, you might have a shopping cart bean, stored in session scope for each current user, with properties that represent the current set of items that the user has decided to purchase. This bean might also have a checkOut() method that authorizes the user's credit card and sends the order to the warehouse to be picked and shipped. Other systems will represent the available operations separately, perhaps as Session Enterprise JavaBeans (Session EJBs).

In a smaller scale application, on the other hand, the available operations might be embedded within the Action classes that are part of the framework control layer. This can be useful when the logic is very simple or where reuse of the business logic in other environments is not contemplated.

The framework architecture is flexible enough to support most any approach to accessing the Model, but we strongly recommend that you separate the business logic ("how it's done") from the role that Action classes play ("what to do"). 'nuff said.

For more about adapting your application's Model to the framework, see the Building Model Components chapter.

1.2.2 The View: JSP Pages and Presentation Components

The View portion of a Struts-based application is most often constructed using JavaServer Pages (JSP) technology. JSP pages can contain static HTML (or XML) text called "template text", plus the ability to insert dynamic content based on the interpretation (at page request time) of special action tags. The JSP environment includes a set of standard action tags, such as whose purpose is described in the JavaServer Pages Specification. In addition to the built-in actions, there is a standard facility to define your own tags, which are organized into "custom tag libraries."

The framework includes a set of custom tag libraries that facilitate creating user interfaces that are fully internationalized and interact gracefully with ActionForm beans. ActionForms capture and validate whatever input is required by the application.

For more about the Struts taglibs and using presentation pages with the framework, see the Building View Components section. Additional documentation regarding the taglibs is also available in the Taglibs subproject.

1.2.3 The Controller: ActionServlet and ActionMapping

Struts provides the Controller portion of the application. The Controller is focused on receiving requests from the client (typically a user running a web browser), deciding what business logic function is to be performed, and then delegating responsibility for producing the next phase of the user interface to an appropriate View component. The primary component of the Controller in the framework is a servlet of class ActionServlet. This servlet is configured by defining a set of ActionMappings. An ActionMapping defines a path that is matched against the request URI of the incoming request and usually specifies the fully qualified class name of an Action class. All Actions are subclassed from [org.apache.struts.action.Action]. Actions encapsulate calls to business logic classes, interpret the outcome, and ultimately dispatch control to the appropriate View component to create the response. While the framework dispatches to a View, actually rendering the View is outside its scope.

The framework also supports the ability to use ActionMapping classes that have additional properties beyond the standard ones required to operate the controller. This allows you to store additional information specific to your application and still utilize the remaining features of the framework. In addition, the framework lets you define logical "names" to which control should be forwarded so that an action method can ask for the "Main Menu" page (for example), without knowing the location of the corresponding JSP page. These features greatly assist you in separating the control logic (what to do) with the view logic (how it's rendered).

For more about the control layer, see the Building Controller Components chapter.

1.3 Framework Control Flow

The framework provides several components that make up the Control layer of a MVC-style application. These include a controller component (servlet), developer-defined request handlers, and several supporting objects.

The Struts Taglib component provides direct support for the View layer of a MVC application. Some of these tags access the control-layer objects. Others are generic tags found convenient when writing applications. Other taglibs, including JSTL, can also be used with the framework. Other presentation technologies, like Velocity Templates and XSLT can also be used with the framework.

The Model layer in a MVC application is often project-specific. The framework is designed to make it easy to access the business-end of your application, but leaves that part of the programming to other products, like JDBC, Enterprise Java Beans,Object Relational Bridge, or iBATIS, to name a few.

Let's step through how this all fits together.

When initialized, the controller parses a configuration file (struts-config.xml) and uses it to deploy other control layer objects. Together, these objects form the Struts Configuration. The Configuration defines (among other things) the collection of ActionMappings[org.apache.struts.action.ActionMappings] for an application.

The controller component consults the ActionMappings as it routes HTTP requests to other components in the framework. Requests may be forwarded to JavaServer Pages or Action[org.apache.struts.action.Action] subclasses provided by the application developer. Often, a request is first forwarded to an Action and then to a JSP (or other presentation page). The mappings help the controller turn HTTP requests into application actions.

An individual ActionMapping[org.apache.struts.action.ActionMapping] will usually contain a number of properties including:

    a request path (or "URI"),
    the object type (Action subclass) to act upon the request, and
    other properties as needed.

The Action object can handle the request and respond to the client (usually a Web browser) or indicate that control should be forwarded elsewhere. For example, if a login succeeds, a login action may wish to forward the request onto the mainMenu page.

Action objects have access to the application's controller component, and so have access to that members's methods. When forwarding control, an Action object can indirectly forward one or more shared objects, including JavaBeans, by placing them in one of the standard contexts shared by Java Servlets.

For example, an Action object can create a shopping cart bean, add an item to the cart, place the bean in the session context, and then forward control to another mapping. That mapping may use a JavaServer Page to display the contents of the user's cart. Since each client has their own session, they will each also have their own shopping cart.

Most of the business logic in an application can be represented using JavaBeans. An Action can call the properties of a JavaBean without knowing how it actually works. This encapsulates the business logic, so that the Action can focus on error handling and where to forward control.

JavaBeans can also be used to manage input forms. A key problem in designing Web applications is retaining and validating what a user has entered between requests. You can define your own set of input bean classes, by subclassing ActionForm[org.apache.struts.action.ActionForm]. The ActionForm class makes it easy to store and validate the data for your application's input forms. The ActionForm bean is automatically saved in one of the standard, shared context collections, so that it can be used by other objects, like an Action object or another JSP.

The form bean can be used by a JSP to collect data from the user ... by an Action object to validate the user-entered data ... and then by the JSP again to re-populate the form fields. In the case of validation errors, the framework has a shared mechanism for raising and displaying error messages.

Another element of the Configuration are the ActionFormBeans[org.apache.struts.action.ActionFormBeans]. This is a collection of descriptor objects that are used to create instances of the ActionForm objects at runtime. When a mapping needs an ActionForm, the servlet looks up the form-bean descriptor by name and uses it to create an ActionForm instance of the specified type.

Here is the sequence of events that occur when a request calls for an mapping that uses an ActionForm:

    The controller servlet either retrieves or creates the ActionForm bean instance.
    The controller servlet passes the bean to the Action object.
    If the request is being used to submit an input page, the Action object can examine the data. If necessary, the data can be sent back to the input form along with a list of messages to display on the page. Otherwise the data can be passed along to the business tier.
    If the request is being used to create an input page, the Action object can populate the bean with any data that the input page might need.

The Struts Taglib component provides custom tags that can automatically populate fields from a JavaBean. All most JavaServer Pages really need to know is the field names to use and where to submit the form.

Other tags can automatically output messages queued by an Action or ActionForm and simply need to be integrated into the page's markup. The messages are designed for localization and will render the best available message for a user's locale.

The framework and Struts Taglib were designed from the ground-up to support the internationalization features built into the Java platform. All the field labels and messages can be retrieved from a message resource. To provide messages for another language, simply add another file to the resource bundle.

Internationalism aside, other benefits to the message resources approach are consistent labeling between forms, and the ability to review all labels and messages from a central location.

For the simplest applications, an Action object may sometimes handle the business logic associated with a request. However, in most cases, an Action object should invoke another object, usually a JavaBean, to perform the actual business logic. This lets the Action focus on error handling and control flow, rather than business logic. To allow reuse on other platforms, business-logic JavaBeans should not refer to any Web application objects. The Action object should translate needed details from the HTTP request and pass those along to the business-logic beans as regular Java variables.

In a database application, for example:

    A business-logic bean will connect to and query the database,
    The business-logic bean returns the result to the Action,
    The Action stores the result in a form bean in the request,
    The JavaServer Page displays the result in a HTML form.

Hibernate


Hibernate (Java)


Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.

Hibernate is free software that is distributed under the GNU Lesser General Public License.

Hibernate's primary feature is mapping from Java classes to database tables (and from Java data types to SQL data types). Hibernate also provides data query and retrieval facilities. It also generates the SQL calls and attempts to relieve the developer from manual result set handling and object conversion and keep the application portable to all supported SQL databases with little performance overhead.



Mapping
Mapping Java classes to database tables is accomplished through the configuration of an XML file or by using Java Annotations. When using an XML file, Hibernate can generate skeletal source code for the persistence classes. This is unnecessary when annotations are used. Hibernate can use the XML file or the annotations to maintain the database schema.

Facilities to arrange one-to-many and many-to-many relationships between classes are provided. In addition to managing associations between objects, Hibernate can also manage reflexive associations where an object has a one-to-many relationship with other instances of its own type.

Hibernate supports the mapping of custom value types. This makes the following scenarios possible:

    Overriding the default SQL type that Hibernate chooses when mapping a column to a property.
    Mapping Java Enum to columns as if they were regular properties.
    Mapping a single property to multiple columns.


Persistence

Hibernate provides transparent persistence for Plain Old Java Objects (POJOs). The only strict requirement for a persistent class is a no-argument constructor, not necessarily public. Proper behavior in some applications also requires special attention to the equals() and hashCode() methods.[1]

Collections of data objects are typically stored in Java collection objects such as Set and List. Java generics, introduced in Java 5, are supported. Hibernate can be configured to lazy load associated collections. Lazy loading is the default as of Hibernate 3.

Related objects can be configured to cascade operations from one to the other. For example, a parent such as an Album object can be configured to cascade its save and/or delete operation to its child Track objects. This can reduce development time and ensure referential integrity. A dirty checking feature avoids unnecessary database write actions by performing SQL updates only on the modified fields of persistent objects.

Hibernate Query Language (HQL)

Hibernate provides an SQL inspired language called Hibernate Query Language (HQL) which allows SQL-like queries to be written against Hibernate's data objects. Criteria Queries are provided as an object-oriented alternative to HQL.
Integration

Hibernate can be used both in standalone Java applications and in Java EE applications using servlets, EJB session beans, and JBI service components. It can also be included as a feature in other programming languages. For example, Adobe integrated Hibernate into version 9 of ColdFusion (which runs on J2EE app servers) with an abstraction layer of new functions and syntax added into CFML.
Entities and components

In Hibernate jargon, an entity is a stand-alone object in Hibernate's persistent mechanism which can be manipulated independently of other objects. In contrast, a component is subordinate to other entities and can be manipulated only with respect to other entities. For example, an Album object may represent an entity but the Tracks object associated with the Album objects would represent a component of the Album entity if it is assumed that Tracks can only be saved or retrieved from the database through the Album object. Unlike J2EE, it can switch databases.
History

Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style entity beans. Its mission back then was to simply offer better persistence capabilities than offered by EJB2 by simplifying the complexities and allowing for missing features.

Early in 2003, the Hibernate development team began Hibernate2 releases which offered many significant improvements over the first release.

JBoss, Inc. (now part of Red Hat) later hired the lead Hibernate developers and worked with them in supporting Hibernate.

In 2010, Hibernate version 3.x was released with the features like: a new Interceptor/Callback architecture, user defined filters, and JDK 5.0 Annotations (Java's metadata feature). As of 2010 Hibernate 3 (version 3.5.0 and up) was a certified implementation of the Java Persistence API 2.0 specification via a wrapper for the Core module which provides conformity with the JSR 317 standard.[2]

In Dec 2011, Hibernate Core 4.0.0 Final was released. This includes new features like: Initial multi-tenancy support, Introduction of ServiceRegistry (which is a major change in how Hibernate builds and manages "services"), Clean up of Session opening from SessionFactory, Improved integration via org.hibernate.integrator.spi.Integrator and auto discovery, Improved logging with i18n support and message codes, Initial work on more clear split between API, SPI and implementation classes, Clean up of deprecated methods, classes, etc.[3]

In 2012, Hibernate 5 started development. It will contain JPA 2.1 support.
Application programming interface

The Hibernate API is provided in the Java package org.hibernate.
org.hibernate.SessionFactory interface

References immutable and threadsafe object creating new Hibernate sessions. Hibernate-based applications are usually designed to make use only of a single instance of the class implementing this interface (often exposed using a singleton design pattern).
org.hibernate.Session interface

Represents a Hibernate session i.e. the main point of the manipulation performed on the database entities. The latter activities include (among the other things) managing the persistence state (transient, persisted, detached[clarification needed]) of the objects, fetching the persisted ones from the database and the management of the transaction demarcation[clarification needed].

A session is intended to last as long as the logical transaction on the database. Due to the latter feature, Session implementations are not expected to be threadsafe nor to be used by multiple clients.
Software components

The Hibernate software includes the following components:[4]


    Hibernate ORM (was known as Hibernate Core before release 4.1[5]) – the base software for an object-relational mapping solution for Java environments[6]
    Hibernate Annotations (merged into Hibernate Core/ORM since version 3.6[7]) – metadata that governs the transformation of data between the object-oriented model and the relational database model according to the JSR 317 Java Persistence API (JPA 2)[8]
    Hibernate EntityManager – together with Hibernate Annotations, a wrapper that implements a JSR 317 Java Persistence API (JPA 2) persistence solution on top of Hibernate Core[9]
    Hibernate Envers – auditing and versioning of persistent classes[10]
    Hibernate OGM – Object/Grid Mapper is an extension to store data in a NoSQL store[11]
    Hibernate Shards – horizontal partitioning for multiple relational databases[12]
        NOTE: Hibernate Shards is not compatible with the 4.x versions of Hibernate Core... some of the Shards capability was integrated into Core in the 4.0 release.
    Hibernate Search – integrates the full text library functionality from Apache Lucene in the Hibernate and JPA model[13]
    Hibernate Tools – a set of tools implemented as a suite of Eclipse plugins and Ant tasks included in JBoss Developer Studio[14]
    Hibernate Validator – the reference implementation of JSR 303 Bean Validation[15]
    Hibernate Metamodel Generator – an annotation processor that creates JSR 317 Java Persistence API (JPA 2) static metamodel classes using the JSR 269 Pluggable Annotation Processing API[16]
    NHibernate – an object-relational mapping solution for the .NET Framework[17]

Monday, 13 August 2012

How to connect Java Application with Oracle Database using JDBC Driver



How to connect Java Application with Oracle Database using JDBC Driver -

Today I will go through the basic steps to connect a Java Application with Oracle Database using JDBC Driver (Java Database Connectivity). To develop Enterprise Product connectivity of java application and oracle database is essential. When I was new to java, i have faced some problem for java and database connectivity using jdbc. So I want to make all this process bit easier for all the new comer in java and windows platform.





Prerequisites :

    Microsoft Windows Xp Service Pack 2 or above.
    Java Developement Kit.
    Oracle Database.
    Oracle JDBC Driver.According to your database version.
    One Integrated Development Environment.like Netbeans,Eclipse

Steps for configuring the system and creating DSN (ODBC Data Source):

    1.Install Java Development Kit and Oracle Database.
    2.Place Oracle JDBC Driver (*.jar file) in java runtime folder and java development kit folder . eg: 'C:\Program Files\Java\jre1.6.0\lib\ext' and 'C:\Program Files\Java\jdk1.6.0\jre\lib\ext'.
   3. Create a Data Source Name (DSN) required for database connectivity in windows.
    For DSN go to Start->Control Panel->Administrative Tools->Data Sources (ODBC).
    4.ODBC Data Source Administrator will open. Click on the Add button to create a new data source.
    





5.Select 'Microsoft ODBC for Oracle' & click Next.



 7.Fill the Data Source Name - name for the data source, Description - Just a simple description, User Name - Oracle Database User name, Server - name of the server where database is installed ,( localhost - if it is installed in the local machine or the IP if the the database is installed in a remote machine). Click OK and close the ODBC Data Source Administrator.







Now, the system is configured to run any java oracle connectivity program.You can start coding the program in any IDE or open a notpad.

Below is the source code of a jdbc program to determine wheather all your setting are OK or not. Compile the program and execute it. If the program is executed without any error or exception and you get 'JDBC Driver loaded' and 'Connected to the Oracle Database' as output then you have done all the setting correctly and you are able to connect to the oracle database through your java program.
If you encounter any problem please get back to me, I will help you to sought out the problem.


Source code :

import java.sql.*;

public class ConnectOracle {

public static void main(String[] args) {
String driver="sun.jdbc.odbc.JdbcOdbcDriver"; //
String cs="jdbc:odbc:connectOracle"; //connectOracle is the data source name
String user = "system"; //username of oracle database
String pwd = "tom"; //password of oracle database
Connection con = null; //connection variable assigned to null
try
{
Class.forName(driver);// for loading the jdbc driver
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("JDBC Driver loaded");
try
{
con=DriverManager.getConnection(cs,user,pwd);// for establishing connection with database
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Connected to the Oracle Database");
try
{
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}//end of main()
}//end of class()

ODBC Driver for Access 2000, 2002, 2003 and 2007 Databases

The Easysoft ODBC-Access Driver connects 32-bit and 64-bit applications on Linux and Unix to Microsoft Access databases.

To ensure compatibility with databases created in as many versions of Access as possible, the Easysoft ODBC-Access Driver supports both the MDB and ACCDB database formats. The Easysoft ODBC-Access Driver can connect to .mdb databases created in Access 2000–2003 and Office Access 2007. The forthcoming release of Access, Office Access 2010, will continue to support .mdb format databases. The Easysoft ODBC-Access Driver can also connect to .accdb databases, which is the default format for databases created in Office Access 2007 and later. The Easysoft ODBC-Access Driver is a flexible, future-proof solution therefore, which will integrate Linux/Unix with whatever version of Access suits your organisation best.

The Easysoft ODBC-Access Driver provides read-write access to Access databases, so your Linux/Unix applications can update as well as retrieve Access data. If you need to restrict users to read-only access, you can configure the driver to open the database in read-only mode, just as you can with the Access front-end application on Windows.

Choosing the Easysoft ODBC-Access Driver to connect Linux/Unix with Access will not disrupt your existing Access solution’s environment or users. There is no software to install on your Windows machines. You do not need to change where your database file is located. The Easysoft ODBC-Access Driver can open an Access database stored on a Windows share, so there is no need to copy the database file to your Linux/Unix machine. To ensure concurrent access to the database by Windows and Linux/Unix users is problem free, the Easysoft ODBC-Access Driver uses Access’ locking file mechanism. The driver will also prevent its users from opening a database if another user has the database opened for exclusive access, again mirroring the Access front-end’s behaviour for seamless integration.

The Easysoft ODBC-Access Driver supports encrypted/encoded .mdb files, which is an Access security feature that protects Access data from unauthorised viewing. When you use the Easysoft ODBC-Access Driver to load a remote .mdb file, encrypting/encoding the database protects the privacy of the Access data as it is sent across the network.

To ensure compatibility with multiple Linux/Unix applications, the Easysoft ODBC-Access Driver supports the unixODBC driver manager. Most (if not all) Linux/Unix applications support unixODBC, which, as a mature, non-proprietary, robust driver manager, is part of the standard installation of many Linux distributions. To provide a self-contained solution, the Easysoft ODBC-Access Driver distribution itself includes the unixODBC driver manager. To get you going quickly, the Easysoft ODBC-Access Driver automatically installs itself into unixODBC, making the driver immediately available to your applications.
Platforms

The Easysoft ODBC-Access Driver is currently available on these platforms:
Version     Platform     Distribution
v1.0 (Access 2000 - 2007)     AIX (PPC) (32 - Bit)     (4.3-6.1)
v1.0 (Access 2000 - 2007)     AIX (PPC) (64 - Bit)     (5.0-6.1)
v1.0 (Access 2000 - 2007)     HP-UX (Itanium i64) (32 - Bit)     (11i)
v1.0 (Access 2000 - 2007)     HP-UX (Itanium i64) (64 - Bit)     (11i)
v1.0 (Access 2000 - 2007)     HP-UX (PA-Risc) (32 - Bit)     (10.10-11)
v1.0 (Access 2000 - 2007)     HP-UX (PA-Risc 2) (64 - Bit)     (11)
v1.0 (Access 2000 - 2007)     Linux (x86) (32 - Bit)     (kernel 2.2-2.6, glibc 2.1+)
v1.0 (Access 2000 - 2007)     Linux (x86) (64 - Bit)     (kernel 2.6, glibc 2.3.5)
v1.0 (Access 2000 - 2007)     Solaris (Sparc) (32 - Bit)     (2.6-2.10)
v1.0 (Access 2000 - 2007)     Solaris (Sparc) (64 - Bit)     (2.8-2.10)
v1.0 (Access 2000 - 2007)     Solaris (x86) (32 - Bit)     (2.8)
v1.0 (Access 2000 - 2007)     Solaris (x86) (64 - Bit)     (2.8)

If the Access ODBC driver is not available for your platform, we have an alternative Access solution, which is available for additional Unix platforms.

Download Access ODBC driver.
MSAccess Linux ODBC Driver

Connects to MS Access databases (.mdb or .accdb) from 32-bit and 64-bit Linux platforms such as CentOS, Debian GNU/Linux, Fedora, Kubuntu/Ubuntu (Edgy Eft/Feisty Fawn/Gutsy Gibbon/Hardy Heron/Intrepid Ibex/Jaunty Jackalope/Karmic Koala), Mandrake/Mandriva, OpenSUSE/SUSE, Red Hat, Slackware and more.
MSAccess Unix ODBC Driver

Connects to MS Access databases (.mdb or .accdb) from 32-bit and 64-bit IBM AIX, HP-UX and Sun Solaris platforms.