Exercise: Implementing the admin_departments Componentized Template

Một phần của tài liệu Beginning PHP and Postgre SQL E-Commerce From Novice to Professional phần 4 ppsx (Trang 49 - 57)

1. Create a new template file named admin_departments.tplin the presentation/templatesfolder, and add the following code to it:

{* admin_departments.tpl *}

{load_admin_departments assign="admin_departments"}

<span class="admin_page_text">Edit the departments of HatShop:</span>

<br /><br />

{if $admin_departments->mErrorMessage neq ""}

<span class="admin_error_text">

{$admin_departments->mErrorMessage}<br /><br />

</span>

{/if}

<form method="post"

action="{$admin_departments->mAdminDepartmentsTarget|prepare_link:"https"}">

{if $admin_departments->mDepartmentsCount eq 0}

<strong>There are no departments in your database!</strong><br />

{else}

<table>

<tr>

<th>Department Name</th>

<th>Department Description</th>

<th>&nbsp;</th>

</tr>

{section name=cDepartments loop=$admin_departments->mDepartments}

{if $admin_departments->mEditItem ==

$admin_departments->mDepartments[cDepartments].department_id}

<tr>

<td width="122">

<input type="text" name="name"

value="{$admin_departments->mDepartments[cDepartments].name}" />

</td>

<td>

{strip}

<textarea name="description" rows="3" cols="42">

{$admin_departments->mDepartments[cDepartments].description}

</textarea>

{/strip}

</td>

<td align="right" width="280">

<input type="submit"

name="submit_edit_categ_{

$admin_departments->mDepartments[cDepartments].department_id}"

value="Edit Categories" />

<input type="submit"

name="submit_update_dep_{

$admin_departments->mDepartments[cDepartments].department_id}"

value="Update" />

<input type="submit" name="cancel" value="Cancel" />

<input type="submit"

name="submit_delete_dep_{

$admin_departments->mDepartments[cDepartments].department_id}"

value="Delete" />

</td>

</tr>

{else}

<tr>

<td width="122">

{$admin_departments->mDepartments[cDepartments].name}

</td>

<td>{$admin_departments->mDepartments[cDepartments].description}</td>

<td align="right" width="280">

<input type="submit"

name="submit_edit_categ_{

$admin_departments->mDepartments[cDepartments].department_id}"

value="Edit Categories" />

<input type="submit"

name="submit_edit_dep_{

$admin_departments->mDepartments[cDepartments].department_id}"

value="Edit" />

<input type="submit"

name="submit_delete_dep_{

$admin_departments->mDepartments[cDepartments].department_id}"

value="Delete" />

</td>

</tr>

{/if}

{/section}

</table>

{/if}

<br />

<span class="admin_page_text">Add new department:</span>

<br /><br />

<input type="text" name="department_name" value="[name]" size="30" />

<input type="text" name="department_description" value="[description]"

size="60" />

<input type="submit" name="submit_add_dep_0" value="Add" />

</form>

2. Create a new plugin file named function.load_admin_departments.phpin the presentation/smarty_pluginsfolder, and add the following to it:

<?php

/* Smarty plugin function that gets called when the

load_admin_departments function plugin is loaded from a template */

function smarty_function_load_admin_departments($params, $smarty) {

// Create AdminDepartments object

$admin_departments = new AdminDepartments();

$admin_departments->init();

// Assign template variable

$smarty->assign($params['assign'], $admin_departments);

}

// Class that supports departments admin functionality class AdminDepartments

{

// Public variables available in smarty template public $mDepartmentsCount;

public $mDepartments;

public $mErrorMessage = '';

public $mEditItem;

public $mAdminDepartmentsTarget = 'admin.php?Page=Departments';

// Private members public $mAction = '';

public $mActionedDepartmentId;

// Class constructor

public function __construct() {

// Parse the list with posted variables foreach ($_POST as $key => $value)

// If a submit button was clicked ...

if (substr($key, 0, 6) == 'submit') {

/* Get the position of the last '_' underscore from submit button name e.g strtpos('submit_edit_dep_1', '_') is 16 */

$last_underscore = strrpos($key, '_');

/* Get the scope of submit button

(e.g 'edit_dep' from 'submit_edit_dep_1') */

$this->mAction = substr($key, strlen('submit_'),

$last_underscore - strlen('submit_'));

/* Get the department id targeted by submit button (the number at the end of submit button name) e.g '1' from 'submit_edit_dep_1' */

$this->mActionedDepartmentId = substr($key, $last_underscore + 1);

break;

} }

public function init() {

// If adding a new department ...

if ($this->mAction == 'add_dep') {

$department_name = $_POST['department_name'];

$department_description = $_POST['department_description'];

if ($department_name == null)

$this->mErrorMessage = 'Department name required';

if ($this->mErrorMessage == null)

Catalog::AddDepartment($department_name, $department_description);

}

// If editing an existing department ...

if ($this->mAction == 'edit_dep')

$this->mEditItem = $this->mActionedDepartmentId;

// If updating a department ...

if ($this->mAction == 'update_dep') {

$department_name = $_POST['name'];

$department_description = $_POST['description'];

if ($department_name == null)

$this->mErrorMessage = 'Department name required';

if ($this->mErrorMessage == null)

Catalog::UpdateDepartment($this->mActionedDepartmentId,

$department_name, $department_description);

}

// If deleting a department ...

if ($this->mAction == 'delete_dep') {

$status = Catalog::DeleteDepartment($this->mActionedDepartmentId);

if ($status < 0)

$this->mErrorMessage = 'Department not empty';

}

// If editing department's categories ...

if ($this->mAction == 'edit_categ') {

header('Location: admin.php?Page=Categories&DepartmentID=' .

$this->mActionedDepartmentId);

exit;

}

// Load the list of departments

$this->mDepartments = Catalog::GetDepartmentsWithDescriptions();

$this->mDepartmentsCount = count($this->mDepartments);

} }

?>

3. Modify the admin.phpfile to load the newly created admin_departmentscomponentized template:

// If admin is logged, load the admin page menu

$pageMenuCell = 'admin_menu.tpl';

if (isset ($_GET['Page']))

$admin_page = $_GET['Page'];

// If Page is not explicitly set, assume the Departments page else

$admin_page = 'Departments';

// If logging out ...

if (isset ($_GET['Page']) && ($_GET['Page'] == 'Logout')) {

unset($_SESSION['AdminLogged']);

header('Location: admin.php');

exit;

}

// Choose what admin page to load ...

if ($admin_page == 'Departments')

$pageContentsCell = 'admin_departments.tpl';

}

How It Works: The admin_departments Componentized Template

You wrote a lot of code in this exercise, and you still can’t test anything. This is the tough part about creating the UI first. Still, the code is not that complicated if you look at it. Let’s see how the admin_departments.tpltemplate is done.

Here’s a scheme of the {section}construct used to build the rows of the table:

{section name=cDepartments loop=$admin_departments->mDepartments}

{if $admin_departments->mEditItem ==

$admin_departments->mDepartments[cDepartments].department_id}

<!--

Here goes a form where the administrator can edit the department name and description with Update/Cancel, Edit Categories, and Delete buttons.

//-->

{else}

<!--

Here goes a form that displays the department name and description, and also Edit, Edit Categories, and Delete buttons.

//-->

{/if}

{/section}

By default, the department name and description are not editable, but when you click the Edit button of one department,$admin_departments->mEditItemis set to the department_idvalue of the clicked depart- ment, and the Smarty presentation logic generates editable text boxes instead of labels. This will allow the administrator to edit the selected department’s details (in edit mode, Update/Cancel buttons appear instead of the Edit button, as you saw in the earlier figures).

The Smarty plugin function loaded from the admin_departmentstemplate (in function.

load_admin_departments.php) is executed whenever the user clicks any of these buttons and reacts to the visitor’s action. The function recognizes what button was clicked and knows what to do after parsing the list of posted variables and reading the clicked button’s name. In the departments admin page (see the admin_departments.tpltemplate file), buttons have names such as submit_edit_dep_1.

All button names start with submitand end with the ID of the department. In the middle of the name is the code for the button type, which specifies what operation to do with the mentioned department. A button named submit_edit_dep_1tells the plugin function to enter edit mode for the department with a department_id value of 1.

Note that with the Add department button, the department’s ID specified in the button name becomes irrelevant, because its value is automatically generated by the database (department_idis a SERIALcolumn).

In our case, the button type can be

• add_depfor the Add department buttons

• edit_depfor the Edit department buttons

• update_depfor the Update buttons

• delete_depfor the Delete buttons

• edit_categfor the Edit Categories buttons

Depending on the type of the clicked button, one of the corresponding business tier methods is called. Let’s con- sider these methods next.

Implementing the Business Tier

You called four middle-tier methods from the AdminDepartmentsclass. Now it’s time to add their business tier counterparts:

• GetDepartmentsWithDescriptionsreturns the list of departments to be displayed in the department’s admin page.

• UpdateDepartmentchanges a department’s details. Its parameters are the department’s department_idvalue, its new name, and its new description.

• DeleteDepartmentdeletes the department specified by the department_idparameter.

• AddDepartmentneeds the name and description for the new department because the department_idvalue is automatically generated by the database (the department_id column in the departmenttable is a SERIALcolumn).

Exercise: Implementing the Business Tier

Now it’s time to implement the new methods. Add this code to the Catalogclass in business/catalog.php:

// Retrieves all departments with their descriptions public static function GetDepartmentsWithDescriptions() {

// Build the SQL query

$sql = 'SELECT * FROM catalog_get_departments();';

// Prepare the statement with PDO-specific functionality

$result = DatabaseHandler::Prepare($sql);

return DatabaseHandler::GetAll($result);

}

// Updates department details

public static function UpdateDepartment($departmentId, $departmentName,

$departmentDescription) {

// Build the SQL query

$sql = 'SELECT catalog_update_department(:department_id, :department_name, :department_description);';

// Build the parameters array

$params = array (':department_id' => $departmentId, ':department_name' => $departmentName,

':department_description' => $departmentDescription);

// Prepare the statement with PDO-specific functionality

$result = DatabaseHandler::Prepare($sql);

// Execute the query

return DatabaseHandler::Execute($result, $params);

}

// Deletes a department

public static function DeleteDepartment($departmentId) {

// Build the SQL query

$sql = 'SELECT catalog_delete_department(:department_id);';

// Build the parameters array

$params = array (':department_id' => $departmentId);

// Prepare the statement with PDO-specific functionality

$result = DatabaseHandler::Prepare($sql);

// Execute the query and return the results return DatabaseHandler::GetOne($result, $params);

}

// Add a department

public static function AddDepartment($departmentName, $departmentDescription) {

// Build the SQL query

$sql = 'SELECT catalog_add_department(

:department_name, :department_description);';

// Build the parameters array

$params = array (':department_name' => $departmentName,

':department_description' => $departmentDescription);

// Prepare the statement with PDO-specific functionality

$result = DatabaseHandler::Prepare($sql);

// Execute the query

return DatabaseHandler::Execute($result, $params);

}

Một phần của tài liệu Beginning PHP and Postgre SQL E-Commerce From Novice to Professional phần 4 ppsx (Trang 49 - 57)

Tải bản đầy đủ (PDF)

(63 trang)