Database Reference
In-Depth Information
$dsn
=
"mysql:host="
.
self
::
$host_name
.
";dbname="
.
self
::
$db_name
;
$dbh
=
new
PDO
(
$dsn
,
self
::
$user_name
,
self
::
$password
);
$dbh
->
setAttribute
(
PDO
::
ATTR_ERRMODE
,
PDO
::
ERRMODE_EXCEPTION
);
return
(
$dbh
);
}
}
# end Cookbook
?>
The
connect()
routine within the class is declared using the
static
keyword to make
it a class method rather than an instance method. This designates it as directly callable
without instantiating an object through which to invoke it.
The
new
PDO()
constructor raises an exception if the connection attempt fails. Following
a successful attempt,
connect()
sets the error-handling mode so that other PDO calls
raise exceptions for failure as well. This way, individual calls need not be tested for an
error return value.
Although most PHP examples throughout this topic don't show the
<?php
and
?>
tags,
I've shown them as part of
Cookbook.php
here to emphasize that library files must en‐
close all PHP code within those tags. The PHP interpreter makes no assumptions about
the contents of a library file when it begins parsing it because you might include a file
that contains nothing but HTML. Therefore, you must use
<?php
and
?>
to specify
explicitly which parts of the library file should be considered as PHP code rather than
as HTML, just as you do in the main script.
PHP looks for libraries by searching the directories named in the
include_path
variable
in the PHP initialization file, as described in the introductory part of this recipe.
PHP scripts often are placed in the document tree of your web serv‐
er, and clients can request them directly. For PHP library files, I
recommend that you place them somewhere outside the document
tree, especially if (like
Cookbook.php
) they contain a username and
password.
After installing
Cookbook.php
in one of the
include_path
directories, try it from a test
harness script,
harness.php
:
<?
php
# harness.php: test harness for Cookbook.php library
require_once
"Cookbook.php"
;
try
{
$dbh
=
Cookbook
::
connect
();
print
(
"Connected
\n
"
);
}