Database Access Tutorial
From DragonPHP
Contents |
[edit] Who should read this?
Anyone who has completed Dragon's Create a Registration Page - Part 1 tutorial or already knows the basics of using Controllers and Templates in the DragonPHP Framework and wants to learn how to implement database access. If you have a working Registration Page then go ahead and start learning below. Otherwise check out the Registration Page Code Listing to get up to speed.
[edit] Introduction
Head to the Registration Page Code Listing and start the tutorial with those files in place on your system. You can see what the registration page looks like by entering the address of the page into your browser:http://your.server.location/path/?registration note: the framework will expand ''?registration'' into ''?module=Default&Controller=Registration'' which is supplied in the ''url_mapper.ini'' file.
Here's what it should look like:
Image:RegistrationPageScreenshot.png
[edit] Set-up Database
Now that we have a working Registration page, complete with form validation, we can set up our database access.
[edit] Create Table
Use this SQL code to make our mySQL table (note the plural table name).
CREATE TABLE `user_registration_infos` ( `id` int(11) auto_increment PRIMARY KEY, `user_id` varchar(64) NOT NULL default '', `email_address` text NOT NULL, `date_created` datetime default '0000-00-00 00:00:00' ) ENGINE=InnoDB DEFAULT CHARSET=utf8
[edit] Configuring env_db.ini
The file for database access is BASE_APPLICATION_DIR/conf/env_db.ini
Add the following code to your existing or brand new env_db.ini file:
[tutorial] db_type=mysql db_host=localhost db_name=<name of your db> db_username=<db username> db_password=<db password>
[edit] Create Registration Service
Services are helpers that allow Controllers to retrieve data. This level of abstraction allows the Database or File System calls (which sometimes change) to be hidden from the Controller who can always make the same call and expect the same response from the service.
Create the file BASE_APPLICATION_DIR/lib/service/RegistrationService.php with the following contents:
<?php
require_once(FRAMEWORK_COMMON_DIR . 'LoggerFactory.php');
require_once(FRAMEWORK_SERVICES_DIR . 'ActiveService.php');
require_once(FRAMEWORK_SERVICES_DIR . 'ServiceManager.php');
class RegistrationService extends ActiveService {
private static $_logger;
function __construct(){
// provides access to logging functions
self::$_logger = LoggerFactory::getInstance(get_class());
}
public function sendRegistrationInfo($userId, $emailAddress){
/*
* create a new record in the registration table.
*/
// get a service manager instance which allows contact with the db defined
// the first two arguments are the name of the table in framework form:
// TableName < -- > table_names is a mapping between the parameter listed
// as the table name and the actual table name in the mysql database.
// that's why we pluralized it, remember?
$service = ServiceManager::getInstance('UserRegistrationInfo' , 'UserRegistrationInfo',false,false,'tutorial');
// create an array of the data we want to include -- most was passed in as parameters
$data = array('user_id'=>$userId, 'email_address'=>$emailAddress, 'date_created'=>date('Y-m-d H:i:s'));
// set the data
$service->setData($data);
return $service->create();
}
public function getRegistrationInfo($userId = false){
/* get current registration information from the database */
// same getInstance call as above
$service = ServiceManager::getInstance('UserRegistrationInfo', 'UserRegistrationInfo',false,false,'tutorial');
// send back an object containing all of the rows of the user_registration_infos table
return $service->read();
}
}
[edit] Add Service Calls to Controller
All of the calls to RegistrationService will come from our Registration class.
First let's include the file we just created:
require_once(APPLICATION_LIB_DIR . 'service/RegistrationService.php');
Our next task is to use our new service to insert the new registration into the database. We first get the relevant data, and then we instantiate the RegistrationService and make a call to the function sendRegistrationInfo() at the end of the if statement which covers the case where the form submission validates correctly.
$userId = $request->getParameter('user_id');
$emailAddress = $request->getParameter('email_address');
$service = new RegistrationService();
$service->sendRegistrationInfo($userId, $emailAddress);
Now we can try the form. Just browse over to the registration form and enter a valid user_id and email_address and submit. The only problem is that we would like to see proof that this is working. Let's add a call to RegistrationService::getRegistrationInfo() which will let us display all of the registered users on the Thank You! page.
Add this code just before the thank_you template is returned:
// use the service we already instantiated to call getRegistrationInfo()
$regInfo = $service->getRegistrationInfo();
// pass the information that we get from the service on to the template as an attribute
$this->setAttribute('reg_info', $regInfo);
[edit] Modify Template to Show Registration Info
Now let's modify the file thank_you.tpl to show us a nicely formatted bunch of database rows.
Make your thank_you.tpl match this one:
<html>
<body>
{$template_tile->header}
<br/>
Thank You!
<br/>
<span style="font-weight:bold">user id </span>'{$user_id}' was registered to
<span style="font-weight:bold">email address </span>'{$email_address}'!
<br/>
<!-- Below is the code for displaying info from the database -->
<h3>Current Registered Users:</h3>
<table border=1>
<tr><th>user_id</th><th>email_address</th><th>date_created</th></tr>
{foreach from=$reg_info item=regList}
<tr><td>{$regList->user_id}</td><td>{$regList->email_address}</td><td>{$regList->date_created}</td></tr>
{/foreach}
</table>
{$template_tile->footer}
</body>
</html>
Now each time a new registration is done a complete list of users should appear, like so:
