Zend Framework Basic Tutorial P840

55
Table of Contents Zend Framework Basic Tutorial................................................................................................................ 3 What is Zend Framework?................................................................................................................3 Why Zend Framework?.................................................................................................................... 3 Where you can get it?....................................................................................................................... 3 Whenever You Need Zend Framework?...........................................................................................3 Learn Zend Framework Intro..................................................................................................................... 4 Explaining Anatomy of Zend Framework Application......................................................................... 5 The Application Folder................................................................................................................ 5 The Library Folder.......................................................................................................................6 The Test folder............................................................................................................................. 6 The web_root folder.....................................................................................................................6 Creating Index.php as Single Access File....................................................................................6 Creating Apache .htaccess........................................................................................................... 7 Creating Controller...................................................................................................................... 7 Creating View.............................................................................................................................. 7 Learn Zend Framework Action............................................................................................................. 8 Dynamic Content......................................................................................................................... 8 URL Structure and Controller......................................................................................................9 URL Structure and Action..........................................................................................................10 GET Parameters......................................................................................................................... 11 Including Header and Footer..................................................................................................... 13 Learn Zend Framework Database....................................................................................................... 13 Intro............................................................................................................................................13 Creating Input Form...................................................................................................................14 Inputing Data to Database..........................................................................................................16 Inserting Expressions to a table................................................................................................. 17 Creating List of Data..................................................................................................................18 Creating Editing Form............................................................................................................... 20 Updating Data............................................................................................................................ 21 Updating Data Use Update Query From Zend.......................................................................... 22 Deleting Data............................................................................................................................. 23 Delete Query Style..................................................................................................................... 23 Summarizing Action Controller.................................................................................................24 Learn Zend Framework Registry........................................................................................................ 27 Setting and Reading Values........................................................................................................27 Storing Array Values.................................................................................................................. 28 Working with Objects................................................................................................................ 29 Learn Zend Framework Config...........................................................................................................33 Using Array Configuration........................................................................................................ 33 Creating File Configuration....................................................................................................... 35 Using INI File Configuration.....................................................................................................36 Using XML File Configuration..................................................................................................37 Learn Zend Framework Login............................................................................................................ 37 Preparing Database.................................................................................................................... 37 Creating Form Login..................................................................................................................38 Creating Authentication............................................................................................................. 39

Transcript of Zend Framework Basic Tutorial P840

Page 1: Zend Framework Basic Tutorial P840

Table of ContentsZend Framework Basic Tutorial................................................................................................................3

What is Zend Framework?................................................................................................................3Why Zend Framework?....................................................................................................................3Where you can get it?.......................................................................................................................3Whenever You Need Zend Framework?...........................................................................................3

Learn Zend Framework Intro.....................................................................................................................4Explaining Anatomy of Zend Framework Application.........................................................................5

The Application Folder................................................................................................................5The Library Folder.......................................................................................................................6The Test folder.............................................................................................................................6The web_root folder.....................................................................................................................6Creating Index.php as Single Access File....................................................................................6Creating Apache .htaccess...........................................................................................................7Creating Controller......................................................................................................................7Creating View..............................................................................................................................7

Learn Zend Framework Action.............................................................................................................8Dynamic Content.........................................................................................................................8URL Structure and Controller......................................................................................................9URL Structure and Action..........................................................................................................10GET Parameters.........................................................................................................................11Including Header and Footer.....................................................................................................13

Learn Zend Framework Database.......................................................................................................13Intro............................................................................................................................................13Creating Input Form...................................................................................................................14Inputing Data to Database..........................................................................................................16Inserting Expressions to a table.................................................................................................17Creating List of Data..................................................................................................................18Creating Editing Form...............................................................................................................20Updating Data............................................................................................................................21Updating Data Use Update Query From Zend..........................................................................22Deleting Data.............................................................................................................................23Delete Query Style.....................................................................................................................23Summarizing Action Controller.................................................................................................24

Learn Zend Framework Registry........................................................................................................27Setting and Reading Values........................................................................................................27Storing Array Values..................................................................................................................28Working with Objects................................................................................................................29

Learn Zend Framework Config...........................................................................................................33Using Array Configuration........................................................................................................33Creating File Configuration.......................................................................................................35Using INI File Configuration.....................................................................................................36Using XML File Configuration..................................................................................................37

Learn Zend Framework Login............................................................................................................37Preparing Database....................................................................................................................37Creating Form Login..................................................................................................................38Creating Authentication.............................................................................................................39

Page 2: Zend Framework Basic Tutorial P840

Fatal error Cannot use object of type stdClass as array.............................................................44Protected Page............................................................................................................................44Creating Logout.........................................................................................................................45Creating Switching for Front Page............................................................................................45

Learn Zend Framework Session..........................................................................................................50Introduction................................................................................................................................50Using Namespace.......................................................................................................................51Accessing Session Data.............................................................................................................53Seing All Values at Namespace..................................................................................................53Locking and Unlocking Namespace..........................................................................................54Automatic Expiration.................................................................................................................55

Page 3: Zend Framework Basic Tutorial P840

Zend Framework Basic TutorialZend Framework is open source PHP Framework.

What is Zend Framework?

• framework for building web faster and robust. • Created by the company main supporters of PHP, Zend. • Supporting web 2.0 and cloud computing technologies.

Why Zend Framework?

• Free and open source framework • Extreme Simplicity • High productivity • Flexible Architecture • Supported by more than 300 contributor, include IBM and other major companies

Where you can get it?

• You can download at: http://framework.zend.com/ • There you will also get the framework user community

Whenever You Need Zend Framework?

• When building the web with sufficient complexity

Page 4: Zend Framework Basic Tutorial P840

Learn Zend Framework IntroZend framework is one of popular framework at PHP World. This framework is released by Zend, a big vendor for PHP. In this post, We learn Zend framework from zero. We will build a simple application named "helloworld". In this framework, we use MVC (Model View Controller). We ever talk about this pattern at Joomla MVC. Our target is create simple application like this:

First, create folder structure like this at your web server folder (I create under www/test/zend. Up to you. You can create under www/test or just www).

Then, download zend framework from here. Extract compressed file. You may get structure like this:

Page 5: Zend Framework Basic Tutorial P840

Copy zend library (folder named "zend" under library) to helloworld/library. Thus, your application become like this:

Explaining Anatomy of Zend Framework Application

Zend Framework Step By Step Tutorial - Part 2: We have created folder structure for helloword applicaton use zend framework. What we created is standard for Model View Controller pattern at zend framework application. In this post, we will see what function each folders. There are 4 top level directories within application's folder:1. Application2. library3. test4. web_root

The Application Folder

The application folder contains all the code required to run the application. User can not accessed directly. This is separation between display, business, and control logic modele. Under this application, there are models, views, and controllers folder. These folders contain the model, view, and controller

Page 6: Zend Framework Basic Tutorial P840

files. Other folders still may be created, for example for configuration files.

The Library Folder

All applications use zend library. We place zend framework here. but, substantively, we can store library at anywhere. But make sure the application can find them. You can store at a global include directory that accessible for php application on the server, such as /usr/php_include or c:\code\php_include. Make sure set php.ini configuration file (or you can use set_include_path() function).

The Test folder

This folder is used to store all unit tests that are written. If you still don't know about unit test, you can read at this. many PHP programmers do not place unit test as special step. How about you?

The web_root folder

All web request from user are channeled through a single file, usually called index.php. This file is the only php file that needs to be accessible by web server. This file is placed in the web_root. Other common files that can be accessed directly are images, css, and JavaScript files. Each of them has own sub-directory within web_root directory.

Creating Index.php as Single Access File

Zend Framework Step By Step Tutorial - Part 3: As we know, at Zend Framework, index.php is a file that needed in the web root directory. This file is used for all page request. It is used for setting up the application's environtment, Zend framework's controller system, then running the application itself. This is Front Controller pattern. Create a file named "index.php" within helloworld/web_root. Enter following code:

<?phperror_reporting(E_ALL|E_STRICT);ini_set('display_errors', true);date_default_timezone_set('Europe/London');

$rootDir = dirname(dirname(__FILE__));set_include_path($rootDir . '/library' . PATH_SEPARATOR . get_include_path());

require_once 'Zend/Controller/Front.php';Zend_Controller_Front::run('../application/controllers');

?>

Ok, let's look at this file in more detail. Line 2-4 is used for setup environtment. Line 3 to ensure that all errors or notices are displayed. Line 4 for setup default time zone.

include_path() specifies a list of directories where the require(), include() and fopen_with_path() functions look for files. You can set at php.ini. But, we don't have to do it. We can use set_include_path(). You can see at line 7.

This is the bootstrap file. Bootstrapping is the term used to describe starting the application up. The core of this code at line 9-10. This will instantiate and dispatch the front controller. It will route request

Page 7: Zend Framework Basic Tutorial P840

to action controllers.

Creating Apache .htaccess

Zend Framework Step By Step Tutorial - Part 4: We need route any requests to the front controller. We can use module from apache named "mod_rewrite". About this module, you can read at this post. Then, we will work with .htaccess file. This file will do routing job. Create a file named ".htaccess" within web_root. Then enter following code:

RewriteEngine OnRewriteRule .* index.php

At the line 2, we can see, Apache will route all request to index.php. Simple code, isn't it?

Another option, you can configure it directly in Apache's httpd.conf file. We know, it is not easy way if we don't have own server. Thus, configure in a local Apache configuration file named .htaccess is better option.

Creating Controller

Zend Framework Step By Step Tutorial - Part 5: The front controller pattern maps the URL requested by the user to a particular member function within a specific controller class. We called as routing and dispatching. The controller class have a strict naming convention requirement. The router calls a function named {actionname}Action() within the {ControllerName}Controller class. This class must be within a file called {ControllerName}.php. If not provide, index will be used. Still confuse? look at this example: Create a file named "IndexController.php" within application/controllers. Enter following code:

<?phprequire_once 'Zend/Controller/Action.php';

class IndexController extends Zend_Controller_Action{ public function indexAction() { $this->view->assign('title', 'Hello, World!'); } }?>

Within the front controller system, the dispatcher expects to find a file called IndexController.php within the application/controllers directory. This file must contain a class called Indexcontroller and, as a minimum, contain a function called indexAction().

Creating View

Zend Framework Step By Step Tutorial - Part 6: Now, we need to provide a view template for displaying. We will create a index.phtml file. This file is stored within the views/scripts/index. We have a separate directory for each controllers view templates. Create a file named "index.phtml" within views/scripts/index. Enter following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Page 8: Zend Framework Basic Tutorial P840

<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title><? echo $this->escape($this->title); ?></title></head>

<body> <h1><? echo $this->escape($this->title); ?></h1></body></html>

The template file is executed within a member function of Zend_View and so $this is available within the template file wich is the gateway to Zend_View's functionality. All variables that have been assigned to the view from within the controller are availabel directly as properties of $this. You can see sample at above, $this->title.

Learn Zend Framework Action

Dynamic Content

Zend Framework Action Step By Step Tutorial - Part 1: Previous post, we ever talk little about assign parameter to view. This value is sent from controller. This can happen because Action Controller. I will not talk much detail about Action Controller, but, we will learn implementation of Action Controller in web development. First, just remembering about passing value from controller to view. We wrote code like this:

<?phprequire_once 'Zend/Controller/Action.php';

class IndexController extends Zend_Controller_Action{ public function indexAction() { $this->view->assign('title', 'Hello, World!'); } }?>

View will catch with like this:

<? echo $this->escape($this->title); ?>

If you still don't know what we talk about, please read this series about Zend Framework Introduction.

Ok, now, add one or more parameter such as:

<?phprequire_once 'Zend/Controller/Action.php';

class IndexController extends Zend_Controller_Action{ public function indexAction() { $this->view->assign('title', 'Hello, World!');

Page 9: Zend Framework Basic Tutorial P840

$this->view->assign('wellcome','Wellcome to my site. This site is built using Zend Framework. Enjoy it!'); $this->view->assign('webmaster','Wiwit'); } }?>

Then, change you "index.phtml" within application/views/scripts/index.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title><? echo $this->escape($this->title); ?></title></head>

<body> <h1><? echo $this->escape($this->title); ?></h1> <?=$this->escape($this->wellcome);?> <p>&nbsp;</p> <?=$this->escape($this->webmaster);?></body></html>

Point your browser to http://localhost/test/zend/helloworld/web_root/. May you get like this:

URL Structure and Controller

Zend Framework Action Step By Step Tutorial - Part 2: URL is important part when we develop web application. We use them for jump between pages. As we know, every framework have rule about URL. It is a key to understanding how the framework works. Now, we will talk rule at Zend Framework. Zend Framework breaks URL into pieces. Those pieces are laid out as follows: http://hostname/controller/action/parametes.

Look at our url that we used to access hello page: http://localhost/test/zend/helloworld/web_root/. Assume http://hostname is same with http://localhost/test/zend/helloworld/web_root/. Next path is controller. Try to point your browser to http://localhost/test/zend/helloworld/web_root/index. We get same with http://localhost/test/zend/helloworld/web_root/. Why? as default, http://localhost/test/zend/helloworld/web_root/ will access index controller. Can you catch idea?

I know, you don't patient to test with other controller. How about we use other controller named "user"? Never mind. From theory above, we will access with

Page 10: Zend Framework Basic Tutorial P840

http://localhost/test/zend/helloworld/web_root/user. Let's do it.

First, create controller name "UserController". Create a file named "UserController" within application/controllers. Enter following code:

<?phprequire_once 'Zend/Controller/Action.php';

class UserController extends Zend_Controller_Action{ public function indexAction() { $this->view->assign('name', 'Wiwit'); $this->view->assign('title', 'Hello'); } }?>

Next, create a folder named "user" within helloworld\application\views\scripts. Create a file named "index.phtml" within user. Enter following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title><? echo $this->escape($this->title); ?></title></head>

<body> <h1><?=$this->escape($this->title);?>, <?=$this->escape($this->name);?></h1></body></html>

Now, point your browser to http://localhost/test/zend/helloworld/web_root/user.

URL Structure and Action

Zend Framework Action Step By Step Tutorial - Part 3: Just remember, we have rule like this: http://hostname/controller/action/parametes. We have talked about controller. Now, we discuss next part, action. For simply, action is method in our class at controller. Look at our code:

<?phprequire_once 'Zend/Controller/Action.php';

class UserController extends Zend_Controller_Action{ public function indexAction() { $this->view->assign('name', 'Wiwit'); $this->view->assign('title', 'Hello'); }

Page 11: Zend Framework Basic Tutorial P840

}?>

Above, we have action name "index". Naming in Zend Framework, add with Action. Thus, we have action "indexAction". When we call this controller (such as user), but we don't specify action, it will call indexAction as default.

Now, add a method in there, example "nameAction" such as:

public function nameAction(){ $this->view->assign('name', 'Wiwit'); $this->view->assign('title', 'User Name'); }

Below, complete our userController:

<?phprequire_once 'Zend/Controller/Action.php';

class UserController extends Zend_Controller_Action{ public function indexAction() { $this->view->assign('name', 'Wiwit'); $this->view->assign('title', 'Hello'); }

public function nameAction() { $this->view->assign('name', 'Wiwit'); $this->view->assign('title', 'User Name'); } }?>

Next, create a file named "name.phtml" within views/scrips/user. Enter following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title><? echo $this->escape($this->title); ?></title></head>

<body> <h1><?=$this->escape($this->title);?>, <?=$this->escape($this->name);?></h1></body></html>

Now, point your browser to http://localhost/test/zend/helloworld/web_root/user/name

Page 12: Zend Framework Basic Tutorial P840

GET Parameters

Zend Framework Action Step By Step Tutorial - Part 4: Now, we talk last part or URL in Zend Framework, parameters. Ok, what the rule in Zend Framework? Look this URL sample:

http://hostname/user/name/username/wiwit/gender/man

We can interpret like this:

1. Controller = user 2. Action = name 3. username = wiwit 4. gender = man

What is your conclusion? Yeah, we have general formula like this:

http://hostname/controller/action/var1/value1/var2/value2/...

How to catch the parameters? Ok, we can learn from sample. Open UserController.php within application/controller. Update became like this:

<?phprequire_once 'Zend/Controller/Action.php';

class UserController extends Zend_Controller_Action{ public function indexAction() { $this->view->assign('name', 'Wiwit'); $this->view->assign('title', 'Hello'); } public function nameAction() { $request = $this->getRequest(); $this->view->assign('name', $request->getParam('username')); $this->view->assign('gender', $request->getParam('gender')); $this->view->assign('title', 'User Name'); } }?>

Give attention at line 15-17. It is clear, isn't it?

Last, update your view: "name.phtml":

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title><? echo $this->escape($this->title); ?></title></head>

Page 13: Zend Framework Basic Tutorial P840

<body> <h1><?=$this->escape($this->title);?>, <?=$this->escape($this->name);?></h1> <h2>Gender: <?=$this->escape($this->gender);?></h2></body></html>

Including Header and Footer

Zend Framework Action Step By Step Tutorial - Part 5: Last posting from this series, we talk about how to include header and footer for template. I know, may be this is not any relation with Zend Framework Action, but, may be this knowledge become useful for you to build web site now. Create a file named "header.phtml" within views/scripts/user. Enter following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title><? echo $this->escape($this->title); ?></title></head><body><div id="header">My Zend Framework</div>

Now, create a file named "footer.phtml" within views/scripts/user. Enter following code:

<div id="footer">By PHPEveryday.com</div></body></html>

Last, update "name.phtml" within views/scripts/user with this:

<? include "header.phtml"; ?> <h1><?=$this->escape($this->title);?>, <?=$this->escape($this->name);?></h1> <h2>Gender: <?=$this->escape($this->gender);?></h2><? include "footer.phtml"; ?>

Now, try to point your browser to http://localhost/test/zend/helloworld/web_root/user/ name/username/wiwit/gender/man

Learn Zend Framework Database

Intro

Zend Framework Database Step By Step Tutorial - Part 1: Zend Framework provides classes for supporting database. Name of that class is Zend_Db. More benefit using this class and its related classes is features that offer simple SQL database interface.

Page 14: Zend Framework Basic Tutorial P840

If we talk about database in Zend Framework, we may talk what is Zend_Db_Adapter. This is basic class you use to connect your PHP application to and RDBMS. As we know, there is a different adapter class for each brand of RDBMS. The Zend_Db_Adapters is a bridge from the vendor-specific PHP extensions to a common interface. With this class, you can write PHP application for multi brands of RDBMS (with little effort).

May be you remember there is extension at PHP that have function like Zend_Db_Adapter, PHP Data Object (PDO). PDO provide interface for multi database at PHP 5. At PHP 4, we know a library, ADOdb. About PHP ADOdb, you can read this post.

in this practice, we will use PDO for mysql (pdo_mysql). First try to check availabelity pdo_mysql in your system. Check in your php.ini. uncomment extension=php_pdo.dll,extension=php_pdo_mysql.dll, then restart your apache.

Ok, just remmembering, this practise base on our previous practice. So, make sure that you have followed that practice.

For this practice, create a database named "zend". Then create a table named "user". You can use this query:

CREATE TABLE `user` ( `id` int(11) NOT NULL auto_increment, `first_name` varchar(50) NOT NULL, `last_name` varchar(50) NOT NULL, `user_name` varchar(50) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `user_name` (`user_name`));

Creating Input Form

Zend Framework Database Step By Step Tutorial - Part 2: First step, we will create a form for inputing data. We create this form at User Controller. We just add method named "registerAction" as action for this controller. Open "UserController.php" within application/controllers. Add following method:

public function registerAction() { $request = $this->getRequest();

$this->view->assign('action',"process"); $this->view->assign('title','Member Registration');$this->view->assign('label_fname','First Name');$this->view->assign('label_lname','Last Name'); $this->view->assign('label_uname','User Name'); $this->view->assign('label_pass','Password');$this->view->assign('label_submit','Register'); $this->view->assign('description','Please enter this form completely:'); }

As we know, if we create action name "registerAction", we must create a view named "register.phtml". Ok, create a file named "register.phtml" within application/views/scripts/user. Enter following code:

Page 15: Zend Framework Basic Tutorial P840

<? include "header.phtml"; ?> <h1><?=$this->escape($this->title);?></h1> <div id="description"> <?=$this->escape($this->description);?> </div> <form name="register" method="post" action="<?=$this->escape($this->action)?>"> <table> <tr> <td><?=$this->escape($this->label_fname)?></td> <td><input type="text" name="first_name"></td> </tr> <tr> <td><?=$this->escape($this->label_lname)?></td> <td><input type="text" name="last_name"></td> </tr> <tr> <td><?=$this->escape($this->label_uname)?></td> <td><input type="text" name="user_name"></td> </tr> <tr> <td><?=$this->escape($this->label_pass)?></td> <td><input type="password" name="password"></td> </tr> </table> <input type="submit" name="submit" value="<?=$this->escape($this->label_submit);?>"> </form><? include "footer.phtml"; ?>

Page 16: Zend Framework Basic Tutorial P840

Inputing Data to Database

After create form, now, we create action to input data to database. For this job, open "UserController.php" within application/controllers. Add a method named "processAction", with following code:

public function processAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' );$DB = new Zend_Db_Adapter_Pdo_Mysql($params);

$request = $this->getRequest();

$sql = "INSERT INTO `user` (`first_name` , `last_name` ,`user_name` ,`password`) VALUES ('".$request->getParam('first_name')."', '".$request->getParam('last_name')."', '".$request->getParam('user_name')."', MD5('".$request->getParam('password')."'))";$DB->query($sql);

$this->view->assign('title','Registration Process');$this->view->assign('description','Registration succes');

}

It is simple to understand it, isn't it?

Next, create view for this processAction. create a file named "process.phtml" within application/views/scripts/user

<? include "header.phtml"; ?> <h1><?=$this->escape($this->title);?></h1> <h2><?=$this->escape($this->description);?></h2> <a href="list">Member List</a><? include "footer.phtml"; ?>

Now, point your browser to http://localhost:8050/test/zend/helloworld/web_root/user/register. Then, enter a user information such as:

Page 17: Zend Framework Basic Tutorial P840

Click registration button. You will get like this:

Inserting Expressions to a table

Zend Framework Database Step By Step Tutorial - Part 4: At previous post, we use ordinary query for input data. Zend framework have simple way for insert query. It is good alternative because simple and more neat. You can use like this:

$data = array('first_name' => $request->getParam('first_name'), 'last_name' => $request->getParam('last_name'), 'user_name' => $request->getParam('user_name'), 'password' => md5($request->getParam('password')) ); $DB->insert('user', $data);

old query like this:

$sql = "INSERT INTO `user` (`first_name` , `last_name` ,`user_name` ,`password`) VALUES ('".$request->getParam('first_name')."', '".$request-

Page 18: Zend Framework Basic Tutorial P840

>getParam('last_name')."', '".$request->getParam('user_name')."', MD5('".$request->getParam('password')."'))";$DB->query($sql);

Ok, replace our processAction become like this:

public function processAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' );$DB = new Zend_Db_Adapter_Pdo_Mysql($params);

$request = $this->getRequest();$data = array('first_name' => $request->getParam('first_name'), 'last_name' => $request->getParam('last_name'), 'user_name' => $request->getParam('user_name'), 'password' => md5($request->getParam('password')) ); $DB->insert('user', $data);

$this->view->assign('title','Registration Process');$this->view->assign('description','Registration succes');

}

Creating List of Data

Zend Framework Database Step By Step Tutorial - Part 5: Now, we create table of data that we have inputed. For this job, we create a methode named "listAction" within controller. Then, create view for that list. Open "UserController.php" within application/controllers. Add following method:

public function listAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' );$DB = new Zend_Db_Adapter_Pdo_Mysql($params); $DB->setFetchMode(Zend_Db::FETCH_OBJ);

$sql = "SELECT * FROM `user` ORDER BY user_name ASC";$result = $DB->fetchAssoc($sql);

$this->view->assign('title','Member List');$this->view->assign('description','Below, our members:');$this->view->assign('datas',$result);

Page 19: Zend Framework Basic Tutorial P840

}

Then, create named "list.phtml" within application/views/scripts/user. Enter following code:

<? include "header.phtml"; ?> <h1><?=$this->escape($this->title);?></h1> <h2><?=$this->escape($this->description);?></h2> <a href="register">Register</a> <table border="1"> <tr> <th>ID</th> <th>User Name</th> <th>First Name</th> <th>Last Name</th> <th>Action</th> </tr> <? $datas = $this->datas; for($i = 1; $i<= count($datas);$i++){ ?> <tr> <td><?=$datas[$i]['id']?></td> <td><?=$datas[$i]['user_name']?></td> <td><?=$datas[$i]['first_name']?></td> <td><?=$datas[$i]['last_name']?></td> <td> <a href="edit/id/<?=$datas[$i]['id']?>">Edit</a> | <a href="del/id/<?=$datas[$i]['id']?>">Delete</a> </td> </tr> <? } ?> </table> <? include "footer.phtml"; ?>

Point your browser to http://localhost/test/zend/helloworld/ web_root/user/list

Page 20: Zend Framework Basic Tutorial P840

Creating Editing Form

Zend Framework Database Step By Step Tutorial - Part 6: To create editing form, add a method in controller. In this practice, we add a action named "editAction". This action will show individual data that filtered by GET http parameter.

Open "UserController.php" within application/controllers. Add following method:

public function editAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' );$DB = new Zend_Db_Adapter_Pdo_Mysql($params);

$request = $this->getRequest();$id = $request->getParam("id");

$sql = "SELECT * FROM `user` WHERE id='".$id."'";$result = $DB->fetchRow($sql);

$this->view->assign('data',$result);$this->view->assign('action', $request->getBaseURL()."/user/processedit"); $this->view->assign('title','Member Editing');$this->view->assign('label_fname','First Name');$this->view->assign('label_lname','Last Name'); $this->view->assign('label_uname','User Name'); $this->view->assign('label_pass','Password');$this->view->assign('label_submit','Edit'); $this->view->assign('description','Please update this form completely:'); }

Then, create a file named "edit.phtml" within application/views/scripts/user. Enter following code:

<? include "header.phtml"; ?> <h1><?=$this->escape($this->title);?></h1> <div id="description"> <?=$this->escape($this->description);?> </div> <form name="edit" method="post" action="<?=$this->escape($this->action)?>"> <input type="hidden" name="id" value="<?=$this->data['id']?>"> <table> <tr> <td><?=$this->escape($this->label_fname)?></td> <td><input type="text" name="first_name" value="<?=$this->data['first_name']?>"></td> </tr> <tr> <td><?=$this->escape($this->label_lname)?></td> <td><input type="text" name="last_name" value="<?=$this->data['last_name']?>"></td> </tr> <tr> <td><?=$this->escape($this->label_uname)?></td>

Page 21: Zend Framework Basic Tutorial P840

<td><input type="text" name="user_name" value="<?=$this->data['user_name']?>"></td> </tr> </table> <input type="submit" name="submit" value="<?=$this->escape($this->label_submit);?>"> </form><? include "footer.phtml"; ?>

Then open your table data again at http://localhost/test/zend/helloworld/web_root/user/list. Klik a edit link at one of rows. The page will jump to edit form such as:

Updating Data

Zend Framework Database Step By Step Tutorial - Part 7: In this post, we will see action for updating data. Open your "UserController.php" within application/controller. Enter following new action:

public function processeditAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' );$DB = new Zend_Db_Adapter_Pdo_Mysql($params);$request = $this->getRequest(); $sql = "UPDATE `user` SET `first_name` = '".$request->getParam('first_name')."', `last_name` = '".$request->getParam('last_name')."', `user_name` = '".$request->getParam('user_name')."' WHERE id = '".$request->getParam('id')."'";$DB->query($sql);

$this->view->assign('title','Editing Process');$this->view->assign('description','Editing succes'); }

Page 22: Zend Framework Basic Tutorial P840

Then, create a file named "processedit.phtml" within views/scripts/user. Enter following code:

<? include "header.phtml"; ?> <h1><?=$this->escape($this->title);?></h1> <h2><?=$this->escape($this->description);?></h2> <a href="list">Member List</a><? include "footer.phtml"; ?>

Ok, try to update data from edit form.

Updating Data Use Update Query From Zend

Zend Framework Database Step By Step Tutorial - Part 8: Like insert query, Zend Framework have another option to create update query. It is more simple and neat. You can use like this:

$data = array('first_name' => $request->getParam('first_name'), 'last_name' => $request->getParam('last_name'), 'user_name' => $request->getParam('user_name'), 'password' => md5($request->getParam('password')) );$DB->update('user', $data,'id = 1');

Following complete code for processeditAction method:

public function processeditAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' );$DB = new Zend_Db_Adapter_Pdo_Mysql($params);$request = $this->getRequest();

$data = array('first_name' => $request->getParam('first_name'), 'last_name' => $request->getParam('last_name'), 'user_name' => $request->getParam('user_name'), 'password' => md5($request->getParam('password')) ); $DB->update('user', $data,'id = '.$request->getParam('id')); $this->view->assign('title','Editing Process');$this->view->assign('description','Editing succes'); }

Deleting Data

Zend Framework Database Step By Step Tutorial - Part 9: Last action from this series is delete data. For this job, create new method in controller.

Page 23: Zend Framework Basic Tutorial P840

Open your "UserController.php" within application/controllers. Add new method for delete action (i give name "delAction"):

public function delAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' );$DB = new Zend_Db_Adapter_Pdo_Mysql($params);$request = $this->getRequest();

$sql = "DELETE FROM `user` WHERE id='".$request->getParam('id')."'";$DB->query($sql);

$this->view->assign('title','Delete Data');$this->view->assign('description','Deleting succes'); $this->view->assign('list',$request->getBaseURL()."/user/list");

Next, create a view for this action. Create a file named "del.phtml" within application/views/scripts/user. Enter following code:

<? include "header.phtml"; ?> <h1><?=$this->escape($this->title);?></h1> <h2><?=$this->escape($this->description);?></h2> <a href="<?=$this->escape($this->list);?>">Member List</a><? include "footer.phtml"; ?>

Now, try to test from table data. Click link del at one of rows.

Delete Query Style

Like insert and update, Zend framework have other option for delete query. You can use this style, and i am sure you will be like.

$DB->delete('user', 'id = 3');

Ok, try to update your delAction become like this:

public function delAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' );$DB = new Zend_Db_Adapter_Pdo_Mysql($params);$request = $this->getRequest();

$DB->delete('user', 'id = '.$request->getParam('id'));

$this->view->assign('title','Delete Data');

Page 24: Zend Framework Basic Tutorial P840

$this->view->assign('description','Deleting succes'); $this->view->assign('list',$request->getBaseURL()."/user/list"); }

Ok, now, you are ready to read more about Zend Framework query style at Zend Framework manual guide.

Summarizing Action Controller

This is last post from Zend Framework Database Tutorial series. In this post, you can look complete action that we had talked.

<?phprequire_once 'Zend/Db/Adapter/Pdo/Mysql.php';require_once 'Zend/Controller/Action.php';

class UserController extends Zend_Controller_Action{ public function indexAction() { $this->view->assign('name', 'Wiwit'); $this->view->assign('title', 'Hello'); } public function nameAction() { $request = $this->getRequest(); $this->view->assign('name', $request->getParam('username')); $this->view->assign('gender', $request->getParam('gender')); $this->view->assign('title', 'User Name'); } public function registerAction() { $request = $this->getRequest(); $this->view->assign('action',"process"); $this->view->assign('title','Member Registration'); $this->view->assign('label_fname','First Name'); $this->view->assign('label_lname','Last Name'); $this->view->assign('label_uname','User Name'); $this->view->assign('label_pass','Password'); $this->view->assign('label_submit','Register'); $this->view->assign('description','Please enter this form completely:'); } public function editAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin',

Page 25: Zend Framework Basic Tutorial P840

'dbname' =>'zend' ); $DB = new Zend_Db_Adapter_Pdo_Mysql($params); $request = $this->getRequest(); $id = $request->getParam("id"); $sql = "SELECT * FROM `user` WHERE id='".$id."'"; $result = $DB->fetchRow($sql); $this->view->assign('data',$result); $this->view->assign('action', $request->getBaseURL()."/user/processedit"); $this->view->assign('title','Member Editing'); $this->view->assign('label_fname','First Name'); $this->view->assign('label_lname','Last Name'); $this->view->assign('label_uname','User Name'); $this->view->assign('label_pass','Password'); $this->view->assign('label_submit','Edit'); $this->view->assign('description','Please update this form completely:'); } public function processAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' ); $DB = new Zend_Db_Adapter_Pdo_Mysql($params); $request = $this->getRequest(); $data = array('first_name' => $request->getParam('first_name'), 'last_name' => $request->getParam('last_name'), 'user_name' => $request->getParam('user_name'), 'password' => md5($request->getParam('password')) ); $DB->insert('user', $data); $this->view->assign('title','Registration Process'); $this->view->assign('description','Registration succes'); } public function listAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' ); $DB = new Zend_Db_Adapter_Pdo_Mysql($params); $DB->setFetchMode(Zend_Db::FETCH_OBJ); $sql = "SELECT * FROM `user` ORDER BY user_name ASC"; $result = $DB->fetchAssoc($sql);

Page 26: Zend Framework Basic Tutorial P840

$this->view->assign('title','Member List'); $this->view->assign('description','Below, our members:'); $this->view->assign('datas',$result); } public function processeditAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' ); $DB = new Zend_Db_Adapter_Pdo_Mysql($params); $request = $this->getRequest(); $data = array('first_name' => $request->getParam('first_name'), 'last_name' => $request->getParam('last_name'), 'user_name' => $request->getParam('user_name'), 'password' => md5($request->getParam('password')) ); $DB->update('user', $data,'id = '.$request->getParam('id')); $this->view->assign('title','Editing Process'); $this->view->assign('description','Editing succes'); } public function delAction() { $params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' ); $DB = new Zend_Db_Adapter_Pdo_Mysql($params); $request = $this->getRequest(); $DB->delete('user', 'id = '.$request->getParam('id')); $this->view->assign('title','Delete Data'); $this->view->assign('description','Deleting succes'); $this->view->assign('list',$request->getBaseURL()."/user/list"); } }?>

Learn Zend Framework Registry

Setting and Reading Values

What is registry? It is like global storage. We just register values then we can use throughout

Page 27: Zend Framework Basic Tutorial P840

application. For example, we can store name of application, thus every time we need to display name of application, we just call from registry.

To use registry, we call registry.php from Zend Framework:

require_once 'Zend/Registry.php';

Ok, we practice using registry. We still use our previous practice. Please read that tutorial before. Then, follow this steps:

1. Open "index.php" within "web_root". Enter line 11 - 13:

<?phperror_reporting(E_ALL|E_STRICT);ini_set('display_errors', true);date_default_timezone_set('Europe/London');

$rootDir = dirname(dirname(__FILE__));set_include_path($rootDir . '/library' . PATH_SEPARATOR . get_include_path());

require_once 'Zend/Controller/Front.php';require_once 'Zend/Registry.php';

Zend_Registry::set('title',"My First Application");

Zend_Controller_Front::run('../application/controllers');

?>

2. We set a parameter named "title". We put a value for this parameter.

3. Next, we try to call/read this registry. Open your UserController.php within application/controllers. 4. Update indexAction like this:

public function indexAction(){ $title = Zend_Registry::get('title'); $this->view->assign('name', 'Wiwit'); $this->view->assign('title', $title);}

Test, by pointing your browser to : http://localhost/test/zend/helloworld/web_root/user/.

You may remember a function at PHP that have function like this, define(). Yup, it is like register global parameter.

Storing Array Values

In this part we talk how to register array value and how to read them? Every value that we store at

Page 28: Zend Framework Basic Tutorial P840

registry can we read as array. Ok, follow this steps to understand. Open again your "index.php" within web_root. Update become like this:

<?phperror_reporting(E_ALL|E_STRICT);ini_set('display_errors', true);date_default_timezone_set('Europe/London');

$rootDir = dirname(dirname(__FILE__));set_include_path($rootDir . '/library' . PATH_SEPARATOR . get_include_path());

require_once 'Zend/Controller/Front.php';require_once 'Zend/Registry.php';

Zend_Registry::set('title',"My First Application");

$arrName = array('Ilmia Fatin','Aqila Farzana', 'Imanda Fahrizal');Zend_Registry::set('credits',$arrName);

Zend_Controller_Front::run('../application/controllers');

?>

We register a array parameter named "credits" at line 15-16. How to read it?

Ok, we test by update again "UserController.php". Update at indexAction become:

public function indexAction() { $registry = Zend_Registry::getInstance();

$title = $registry['title'];$credits = $registry['credits'];$strCredit = implode(", ",$credits);

$this->view->assign('name', 'Wiwit'); $this->view->assign('title', $title); $this->view->assign('credits', $strCredit); }

This is another way to read registry. It can we use to read several values from registry.

Ok, before test it. Please update view at index.phtml within application/views/scripts/user. Update with following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title><? echo $this->escape($this->title); ?></title>

Page 29: Zend Framework Basic Tutorial P840

</head>

<body> <h1><?=$this->escape($this->title);?>, <?=$this->escape($this->name);?></h1> credits: <?=$this->escape($this->credits);?></body></html>

Test by point your browser to http://localhost/test/zend/helloworld/web_root/user/.

Working with Objects

We can store object to Zend_Registry. How to apply it? What for? Remember, our practice about Zend Framework database always write database config and connection several times. Each time connect to database, we write connection. We can save (energy), write one and store to registry To register database connection, we can use like this:

$params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' );$DB = new Zend_Db_Adapter_Pdo_Mysql($params); $DB->setFetchMode(Zend_Db::FETCH_OBJ);Zend_Registry::set('DB',$DB);

Then, read:$registry = Zend_Registry::getInstance(); $DB = $registry['DB'];

Ok, for practice, open index.php within web_root. Update become like this:

<?phperror_reporting(E_ALL|E_STRICT);ini_set('display_errors', true);date_default_timezone_set('Europe/London');

$rootDir = dirname(dirname(__FILE__));set_include_path($rootDir . '/library' . PATH_SEPARATOR . get_include_path());

require_once 'Zend/Controller/Front.php';require_once 'Zend/Registry.php';require_once 'Zend/Db/Adapter/Pdo/Mysql.php';

Zend_Registry::set('title',"My First Application");

$arrName = array('Ilmia Fatin','Aqila Farzana', 'Imanda Fahrizal');Zend_Registry::set('credits',$arrName);

$params = array('host' =>'localhost',

Page 30: Zend Framework Basic Tutorial P840

'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' );$DB = new Zend_Db_Adapter_Pdo_Mysql($params); $DB->setFetchMode(Zend_Db::FETCH_OBJ);Zend_Registry::set('DB',$DB);

Zend_Controller_Front::run('../application/controllers');

?>

Next, update "UserController.php" within application/controllers become like this:

<?php

require_once 'Zend/Controller/Action.php';

class UserController extends Zend_Controller_Action{ public function indexAction() { $registry = Zend_Registry::getInstance(); $title = $registry['title']; $credits = $registry['credits']; $strCredit = implode(", ",$credits); $this->view->assign('name', 'Wiwit'); $this->view->assign('title', $title); $this->view->assign('credits', $strCredit); } public function nameAction() { $request = $this->getRequest(); $this->view->assign('name', $request->getParam('username')); $this->view->assign('gender', $request->getParam('gender')); $this->view->assign('title', 'User Name'); } public function registerAction() { $request = $this->getRequest(); $this->view->assign('action',"process"); $this->view->assign('title','Member Registration'); $this->view->assign('label_fname','First Name'); $this->view->assign('label_lname','Last Name'); $this->view->assign('label_uname','User Name'); $this->view->assign('label_pass','Password'); $this->view->assign('label_submit','Register');

Page 31: Zend Framework Basic Tutorial P840

$this->view->assign('description','Please enter this form completely:'); } public function editAction() { $registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $request = $this->getRequest(); $id = $request->getParam("id"); $sql = "SELECT * FROM `user` WHERE id='".$id."'"; $result = $DB->fetchRow($sql); $this->view->assign('data',$result); $this->view->assign('action', $request->getBaseURL()."/user/processedit"); $this->view->assign('title','Member Editing'); $this->view->assign('label_fname','First Name'); $this->view->assign('label_lname','Last Name'); $this->view->assign('label_uname','User Name'); $this->view->assign('label_pass','Password'); $this->view->assign('label_submit','Edit'); $this->view->assign('description','Please update this form completely:'); } public function processAction() { $registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $request = $this->getRequest(); $data = array('first_name' => $request->getParam('first_name'), 'last_name' => $request->getParam('last_name'), 'user_name' => $request->getParam('user_name'), 'password' => md5($request->getParam('password')) ); $DB->insert('user', $data); $this->view->assign('title','Registration Process'); $this->view->assign('description','Registration succes'); } public function listAction() { $registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $sql = "SELECT * FROM `user` ORDER BY user_name ASC"; $result = $DB->fetchAssoc($sql); $this->view->assign('title','Member List'); $this->view->assign('description','Below, our members:'); $this->view->assign('datas',$result);

Page 32: Zend Framework Basic Tutorial P840

} public function processeditAction() { $registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $request = $this->getRequest(); $data = array('first_name' => $request->getParam('first_name'), 'last_name' => $request->getParam('last_name'), 'user_name' => $request->getParam('user_name'), 'password' => md5($request->getParam('password')) ); $DB->update('user', $data,'id = '.$request->getParam('id')); $this->view->assign('title','Editing Process'); $this->view->assign('description','Editing succes'); } public function delAction() { $registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $request = $this->getRequest(); $DB->delete('user', 'id = '.$request->getParam('id')); $this->view->assign('title','Delete Data'); $this->view->assign('description','Deleting succes'); $this->view->assign('list',$request->getBaseURL()."/user/list"); } }?>

Can you see it? It is simple, isn't it?

Learn Zend Framework Config

Using Array Configuration

There are important information where we build a database application such as host of database, database name, user, database, name of application, and so on. These informations are retrieved extensively. It will concise if we put them on a configuration part. Zend Framework have zend_config, is designed to simplify access to and use of configuration data within applications.

In this post, we see how to implement zend_config use array.

Page 33: Zend Framework Basic Tutorial P840

<?phperror_reporting(E_ALL|E_STRICT);ini_set('display_errors', true);date_default_timezone_set('Europe/London');

$rootDir = dirname(dirname(__FILE__));set_include_path($rootDir . '/library' . PATH_SEPARATOR . get_include_path());

require_once 'Zend/Controller/Front.php';require_once 'Zend/Registry.php';require_once 'Zend/Db/Adapter/Pdo/Mysql.php';

Zend_Registry::set('title',"My First Application");

$arrName = array('Ilmia Fatin','Aqila Farzana', 'Imanda Fahrizal');Zend_Registry::set('credits',$arrName);

$params = array('host' =>'localhost', 'username' =>'root', 'password' =>'admin', 'dbname' =>'zend' );$DB = new Zend_Db_Adapter_Pdo_Mysql($params); $DB->setFetchMode(Zend_Db::FETCH_OBJ);Zend_Registry::set('DB',$DB);

Zend_Controller_Front::run('../application/controllers');

?>

That is index.php. Location code above at web_root. Line 14 and 19-23 often use along application. We can put into an array configuration like this:

<?phperror_reporting(E_ALL|E_STRICT);ini_set('display_errors', true);date_default_timezone_set('Europe/London');

$rootDir = dirname(dirname(__FILE__));set_include_path($rootDir . '/library' . PATH_SEPARATOR . get_include_path());

require_once 'Zend/Controller/Front.php';require_once 'Zend/Registry.php';require_once 'Zend/Db/Adapter/Pdo/Mysql.php';require_once 'Zend/Config.php';

$arrConfig = array( 'webhost'=>'localhost', 'appName'=>'My First Zend',

Page 34: Zend Framework Basic Tutorial P840

'database'=>array( 'dbhost'=>'localhost', 'dbname'=>'zend', 'dbuser'=>'root', 'dbpass'=>'admin' ) );

$config = new Zend_Config($arrConfig);

$title = $config->appName;$params = array('host' =>$config->database->dbhost, 'username' =>$config->database->dbuser, 'password' =>$config->database->dbpass, 'dbname' =>$config->database->dbname );

Zend_Registry::set('title',$title);

$arrName = array('Ilmia Fatin','Aqila Farzana', 'Imanda Fahrizal');Zend_Registry::set('credits',$arrName);

$DB = new Zend_Db_Adapter_Pdo_Mysql($params); $DB->setFetchMode(Zend_Db::FETCH_OBJ);Zend_Registry::set('DB',$DB);

Zend_Controller_Front::run('../application/controllers');

?>

First, load Zend/Config.php (see line 13). Then create array that contains configuration (see line 16-25). Next, Create the object-oriented wrapper upon the configuration data (see line 27). Last, example access configuration data see line 29-34.

Creating File Configuration

For easy maintenance, we put configuration data into separated file. For example, config.php. Let's do it.

Create a file named "config.php" within application. Enter following code:

<?return array( 'webhost'=>'localhost', 'appName'=>'My First Zend', 'database'=>array( 'host'=>'localhost', 'dbname'=>'zend', 'username'=>'root', 'password'=>'admin' )

Page 35: Zend Framework Basic Tutorial P840

);?>

To call this file, we can use like this:$config = new Zend_Config(require '../application/config.php');

This is complete code:<?phperror_reporting(E_ALL|E_STRICT);ini_set('display_errors', true);date_default_timezone_set('Europe/London');

$rootDir = dirname(dirname(__FILE__));set_include_path($rootDir . '/library' . PATH_SEPARATOR . get_include_path());

require_once 'Zend/Controller/Front.php';require_once 'Zend/Registry.php';require_once 'Zend/Db/Adapter/Pdo/Mysql.php';require_once 'Zend/Config.php';

$config = new Zend_Config(require '../application/config.php');

$title = $config->appName;$params = $config->database->toArray();

Zend_Registry::set('title',$title);

$arrName = array('Ilmia Fatin','Aqila Farzana', 'Imanda Fahrizal');Zend_Registry::set('credits',$arrName);

$DB = new Zend_Db_Adapter_Pdo_Mysql($params); $DB->setFetchMode(Zend_Db::FETCH_OBJ);Zend_Registry::set('DB',$DB);

Zend_Controller_Front::run('../application/controllers');

?>

Using INI File Configuration

We have learn about how to use zend_config at previous post. Now, we try to implement using ini file.

Create a file named "config.ini" within application. Enter following sample config:

; Production site configuration data[app]webhost = www.example.comtitle = My Zend Frameworkdatabase.host = localhostdatabase.username = rootdatabase.password = admindatabase.dbname = zend

Page 36: Zend Framework Basic Tutorial P840

To read that config, we use like this:

require_once 'Zend/Config/Ini.php';

$config = new Zend_Config_Ini('../application/config.ini','app');

$title = $config->appName;$params = $config->database->toArray();

Following complete code:

<?phperror_reporting(E_ALL|E_STRICT);ini_set('display_errors', true);date_default_timezone_set('Europe/London');

$rootDir = dirname(dirname(__FILE__));set_include_path($rootDir . '/library' . PATH_SEPARATOR . get_include_path());

require_once 'Zend/Controller/Front.php';require_once 'Zend/Registry.php';require_once 'Zend/Db/Adapter/Pdo/Mysql.php';

require_once 'Zend/Config/Ini.php';

$config = new Zend_Config_Ini('../application/config.ini','app');

$title = $config->appName;$params = $config->database->toArray();

Zend_Registry::set('title',$title);

$arrName = array('Ilmia Fatin','Aqila Farzana', 'Imanda Fahrizal');Zend_Registry::set('credits',$arrName);

$DB = new Zend_Db_Adapter_Pdo_Mysql($params); $DB->setFetchMode(Zend_Db::FETCH_OBJ);Zend_Registry::set('DB',$DB);

Zend_Controller_Front::run('../application/controllers');

?>

Using XML File Configuration

This is another alternative to create a configuration file. We can store configuration data in a simple XML format. To read it, we use Zend_Config_Xml().

First, create a XML file named "config.xml" within application. Enter following code:

Page 37: Zend Framework Basic Tutorial P840

<?xml version="1.0"?><configdata> <app> <webhost>localhost</webhost> <database> <host>localhost</host> <username>root</username> <password>admin</password> <dbname>zend</dbname> </database> </app></configdata>

To access it, we can use:

require_once 'Zend/Config/Xml.php';

$config = new Zend_Config_Xml('../application/config.xml','app');

Learn Zend Framework Login

Preparing Database

Login page is a important part for database application. In this tutorial series, we will talk how to create simple login system at Zend Framework. There are several possible scenario, but I will choose login with database. It means, we need database for store member data.

We still use same database from previous practice. The database name is "zend". Now, create table for store members information. The table name is "users". You can use this query:

CREATE TABLE `users` ( `id` int(11) NOT NULL auto_increment, `username` varchar(50) NOT NULL, `password` varchar(255) NOT NULL, `real_name` varchar(50) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`));

Now, try to insert sample member data for example:

INSERT INTO `users` (`id`, `username`, `password`, `real_name`) VALUES (1, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'Administrator');

Above, we insert a member with user name "admin". Actually, his password is admin. But, for security reason, we use MD5(), so that why, password is stored at database is 21232f297a57a5a743894a0e4a801fc3.

Page 38: Zend Framework Basic Tutorial P840

INSERT INTO `zend`.`users` (`id` ,`username` ,`password` ,`real_name`)VALUES (NULL , 'admin', MD5( 'admin' ) , 'Administrator');

This is screenshot if we use phpMyAdmin.

Creating Form Login

To build login system, we need login form. In this post, we will learn how to build simple login form.

First, create a file named "loginform.phtml" within application/views/scripts/user. Enter following code:

<? include "header.phtml"; ?> <h1><?=$this->escape($this->title);?></h1> <form method='post' action='<?=$this->escape($this->action);?>'> <table> <tr> <td><?=$this->escape($this->username);?></td> <td><input type='text' name='username'></td> </tr> <tr> <td><?=$this->escape($this->password);?></td> <td><input type='password' name='password'></td> </tr> </table> <input type='submit' name='login' value='Login'> </form><? include "footer.phtml"; ?>

Next, create loginformAction at controller. Open your UserController.php within application/controllers. Add following loginFormAction() method: public function loginFormAction() { $request = $this->getRequest(); $this->view->assign('action', $request->getBaseURL()."/user/auth"); $this->view->assign('title', 'Login Form'); $this->view->assign('username', 'User Name'); $this->view->assign('password', 'Password'); }

his form send two parameter: username and password. They are sent to user/auth page.

Now, point your browser to http://localhost/test/zend/helloworld/web_root/user/loginform. You may get like this:

Page 39: Zend Framework Basic Tutorial P840

Creating Authentication

After create form login, we need authentication. Data will be checked with existing data at database.

Just remembering, login form send two parameter: username and password. They are sent to user/auth page. So, we must build authAction() at UserController.

authAction() for data validation. The data that sent by login form will be checked at authAction(). Open your "UserController.php". Firs, load Zend/Auth.php and Zend/Auth/Adapter/DbTable.php. Please place at first line before any method():

<phprequire_once 'Zend/Auth.php';require_once 'Zend/Auth/Adapter/DbTable.php';

...>

Add authAction() like this:

public function authAction(){ $request = $this->getRequest(); $registry = Zend_Registry::getInstance();$auth = Zend_Auth::getInstance();

$DB = $registry['DB']; $authAdapter = new Zend_Auth_Adapter_DbTable($DB); $authAdapter->setTableName('users') ->setIdentityColumn('username') ->setCredentialColumn('password');

// Set the input credential values$uname = $request->getParam('username');$paswd = $request->getParam('password'); $authAdapter->setIdentity($uname); $authAdapter->setCredential(md5($paswd));

// Perform the authentication query, saving the result

Page 40: Zend Framework Basic Tutorial P840

$result = $auth->authenticate($authAdapter);

if($result->isValid()){ $data = $authAdapter->getResultRowObject(null,'password'); $auth->getStorage()->write($data); $this->_redirect('/user/userpage');}else{ $this->_redirect('/user/loginform');}}

First, load database adapter from registry (line 3, 6). If you still don't understand about this code, please read tutorial about Zend Framework Database and Zend Framework Registry.

Then, define authentication adapter:

$authAdapter = new Zend_Auth_Adapter_DbTable($DB);

Next, we define table name, column that contains username and password.$authAdapter->setTableName('users') ->setIdentityColumn('username') ->setCredentialColumn('password');

Next, we catch HTTP parameter that contains username and password:

$uname = $request->getParam('username');$paswd = $request->getParam('password'); $authAdapter->setIdentity($uname); $authAdapter->setCredential(md5($paswd));

Next, do authentication: $result = $auth->authenticate($authAdapter);

if($result->isValid()){ $data = $authAdapter->getResultRowObject(null,'password'); $auth->getStorage()->write($data); $this->_redirect('/user/userpage');}else{ $this->_redirect('/user/loginform');}}

If valid user, we will save user data at session using:$data = $authAdapter->getResultRowObject(null,'password');$auth->getStorage()->write($data);

Then, page will be redirect to protected page (named userpage in this tutorial). Next post, we will talk about protected page. It is simple, isn't it?

Ok, this is our complete UserController:

<?php

require_once 'Zend/Controller/Action.php';require_once 'Zend/Auth.php';require_once 'Zend/Auth/Adapter/DbTable.php';

Page 41: Zend Framework Basic Tutorial P840

class UserController extends Zend_Controller_Action{

public function loginFormAction() { $request = $this->getRequest(); $this->view->assign('action', $request->getBaseURL()."/user/auth"); $this->view->assign('title', 'Login Form'); $this->view->assign('username', 'User Name'); $this->view->assign('password', 'Password'); } public function authAction(){ $request = $this->getRequest(); $registry = Zend_Registry::getInstance(); $auth = Zend_Auth::getInstance(); $DB = $registry['DB']; $authAdapter = new Zend_Auth_Adapter_DbTable($DB); $authAdapter->setTableName('users') ->setIdentityColumn('username') ->setCredentialColumn('password'); // Set the input credential values $uname = $request->getParam('username'); $paswd = $request->getParam('password'); $authAdapter->setIdentity($uname); $authAdapter->setCredential(md5($paswd));

// Perform the authentication query, saving the result $result = $auth->authenticate($authAdapter);

if($result->isValid()){ //print_r($result); $data = $authAdapter->getResultRowObject(null,'password'); $auth->getStorage()->write($data); $this->_redirect('/user'); }else{ $this->_redirect('/user/loginform'); } } public function nameAction() { $request = $this->getRequest(); $this->view->assign('name', $request->getParam('username')); $this->view->assign('gender', $request->getParam('gender')); $this->view->assign('title', 'User Name'); }

Page 42: Zend Framework Basic Tutorial P840

public function registerAction() { $request = $this->getRequest(); $this->view->assign('action',"process"); $this->view->assign('title','Member Registration'); $this->view->assign('label_fname','First Name'); $this->view->assign('label_lname','Last Name'); $this->view->assign('label_uname','User Name'); $this->view->assign('label_pass','Password'); $this->view->assign('label_submit','Register'); $this->view->assign('description','Please enter this form completely:'); } public function editAction() { $registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $request = $this->getRequest(); $id = $request->getParam("id"); $sql = "SELECT * FROM `user` WHERE id='".$id."'"; $result = $DB->fetchRow($sql); $this->view->assign('data',$result); $this->view->assign('action', $request->getBaseURL()."/user/processedit"); $this->view->assign('title','Member Editing'); $this->view->assign('label_fname','First Name'); $this->view->assign('label_lname','Last Name'); $this->view->assign('label_uname','User Name'); $this->view->assign('label_pass','Password'); $this->view->assign('label_submit','Edit'); $this->view->assign('description','Please update this form completely:'); } public function processAction() { $registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $request = $this->getRequest(); $data = array('first_name' => $request->getParam('first_name'), 'last_name' => $request->getParam('last_name'), 'user_name' => $request->getParam('user_name'), 'password' => md5($request->getParam('password')) ); $DB->insert('user', $data); $this->view->assign('title','Registration Process'); $this->view->assign('description','Registration succes'); } public function listAction() {

Page 43: Zend Framework Basic Tutorial P840

$registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $sql = "SELECT * FROM `user` ORDER BY user_name ASC"; $result = $DB->fetchAssoc($sql); $this->view->assign('title','Member List'); $this->view->assign('description','Below, our members:'); $this->view->assign('datas',$result); } public function processeditAction() { $registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $request = $this->getRequest(); $data = array('first_name' => $request->getParam('first_name'), 'last_name' => $request->getParam('last_name'), 'user_name' => $request->getParam('user_name'), 'password' => md5($request->getParam('password')) ); $DB->update('user', $data,'id = '.$request->getParam('id')); $this->view->assign('title','Editing Process'); $this->view->assign('description','Editing succes'); } public function delAction() { $registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $request = $this->getRequest(); $DB->delete('user', 'id = '.$request->getParam('id')); $this->view->assign('title','Delete Data'); $this->view->assign('description','Deleting succes'); $this->view->assign('list',$request->getBaseURL()."/user/list"); } }?>

Page 44: Zend Framework Basic Tutorial P840

Fatal error Cannot use object of type stdClass as array

We run previous post, I get error message like this: Fatal error: Cannot use object of type stdClass as array in C:\AppServ5\www\test\zend\helloworld\ library\Zend\Auth\Adapter\DbTable.php on line 340. If you are same like me, let's fix this problem. Skip this post if you don't fine any error at previous post.

Sadly, I still didn't have much time to know about this error when I was writing this post. So, I decide to fix at core of Zend library. I will tell you latter if I find fixing this error more better than this post.

Ok, open DbTable.php within library\Zend\Auth\Adapter\. Update line 340:

before:

if ($resultIdentity['zend_auth_credential_match'] != '1') {

become?

if ($resultIdentity->zend_auth_credential_match != '1') {

Then, update line 346:

unset($resultIdentity['zend_auth_credential_match']);

become:

unset($resultIdentity->zend_auth_credential_match);

I will update this post if there is more better than this way. Do you want to share idea?

Protected Page

We have created authentication at previous post. Now, we try to protect a page. Thus, when not member try to enter the page, they will be redirected to login form. First, create view. Create a file named "userpage.phtml" within application/views/scripts/user. Enter following code:

<? include "header.phtml"; ?><h1>Hello, <?=$this->escape($this->username);?></h1><a href='<?=$this->escape($this->urllogout);?>'>Logout</a><? include "footer.phtml"; ?>

Then, we add method at controller. Open "UserController.php". Add following method:

public function userPageAction(){ $auth = Zend_Auth::getInstance(); if(!$auth->hasIdentity()){ $this->_redirect('/user/loginform');

Page 45: Zend Framework Basic Tutorial P840

} $request = $this->getRequest(); $user = $auth->getIdentity(); $real_name = $user->real_name; $username = $user->username; $logoutUrl = $request->getBaseURL().'/user/logout';

$this->view->assign('username', $real_name); $this->view->assign('urllogout',$logoutUrl);}

Line 2 - 6 we needed to protect page from unlogin users.

Try to login. You can point your browser to http://localhost/test/zend/helloworld/web_root/user/loginform. Then login.

Creating Logout

At protected page (in previous post), we had created a link to logout. This post talk about logout page. First, create view for logout. Create a file named "logout.phtml" within application/views/scripts/user. Leave blank (because we don't want to show anything).

Then, we create a method for controller named logoutAction(). Open "UserController.php" within application/controllers. Add following method:

public function logoutAction() { $auth = Zend_Auth::getInstance();$auth->clearIdentity();$this->_redirect('/user'); }

We just use clearIdentity(). Then redirect page to another page (in this sample to user).

Creating Switching for Front Page

This is last post from this tutorial series. We will modify front page (user/index). When visitors access this page, they will be redirected to form login. Open "UserController.php" within application/controllers. Update indexAction():

public function indexAction() { $request = $this->getRequest(); $auth = Zend_Auth::getInstance(); if(!$auth->hasIdentity()){ $this->_redirect('/user/loginform');}else{ $this->_redirect('/user/userpage');} }

Page 46: Zend Framework Basic Tutorial P840

Ok, below complete code for controller for this session:

<?php

require_once 'Zend/Controller/Action.php';require_once 'Zend/Auth.php';require_once 'Zend/Auth/Adapter/DbTable.php';

class UserController extends Zend_Controller_Action{ public function indexAction() { $request = $this->getRequest(); $auth = Zend_Auth::getInstance(); if(!$auth->hasIdentity()){ $this->_redirect('/user/loginform'); }else{ $this->_redirect('/user/userpage'); } } public function userPageAction(){

$auth = Zend_Auth::getInstance(); if(!$auth->hasIdentity()){ $this->_redirect('/user/loginform'); }

$request = $this->getRequest(); $user = $auth->getIdentity(); $real_name = $user->real_name; $username = $user->username; $logoutUrl = $request->getBaseURL().'/user/logout';

$this->view->assign('real_name', $real_name); $this->view->assign('urllogout',$logoutUrl); } public function loginFormAction() { $request = $this->getRequest(); $this->view->assign('action', $request->getBaseURL()."/user/auth"); $this->view->assign('title', 'Login Form'); $this->view->assign('username', 'User Name'); $this->view->assign('password', 'Password'); } public function authAction(){ $request = $this->getRequest(); $registry = Zend_Registry::getInstance(); $auth = Zend_Auth::getInstance(); $DB = $registry['DB'];

Page 47: Zend Framework Basic Tutorial P840

$authAdapter = new Zend_Auth_Adapter_DbTable($DB); $authAdapter->setTableName('users') ->setIdentityColumn('username') ->setCredentialColumn('password'); // Set the input credential values $uname = $request->getParam('username'); $paswd = $request->getParam('password'); $authAdapter->setIdentity($uname); $authAdapter->setCredential(md5($paswd));

// Perform the authentication query, saving the result $result = $auth->authenticate($authAdapter);

if($result->isValid()){ //print_r($result); $data = $authAdapter->getResultRowObject(null,'password'); $auth->getStorage()->write($data); $this->_redirect('/user'); }else{ $this->_redirect('/user/loginform'); } } public function logoutAction() { $auth = Zend_Auth::getInstance(); if(!$auth->hasIdentity()){ $this->_redirect('/user/loginform'); }

$auth->clearIdentity(); $this->_redirect('/user'); } public function nameAction() {

$auth = Zend_Auth::getInstance(); if(!$auth->hasIdentity()){ $this->_redirect('/user/loginform'); }

$request = $this->getRequest(); $this->view->assign('name', $request->getParam('username')); $this->view->assign('gender', $request->getParam('gender')); $this->view->assign('title', 'User Name'); } public function registerAction() { $auth = Zend_Auth::getInstance();

Page 48: Zend Framework Basic Tutorial P840

if(!$auth->hasIdentity()){ $this->_redirect('/user/loginform'); } $request = $this->getRequest(); $this->view->assign('action',"process"); $this->view->assign('title','Member Registration'); $this->view->assign('label_fname','First Name'); $this->view->assign('label_lname','Last Name'); $this->view->assign('label_uname','User Name'); $this->view->assign('label_pass','Password'); $this->view->assign('label_submit','Register'); $this->view->assign('description','Please enter this form completely:'); } public function editAction() { $auth = Zend_Auth::getInstance(); if(!$auth->hasIdentity()){ $this->_redirect('/user/loginform'); } $registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $request = $this->getRequest(); $id = $request->getParam("id"); $sql = "SELECT * FROM `user` WHERE id='".$id."'"; $result = $DB->fetchRow($sql); $this->view->assign('data',$result); $this->view->assign('action', $request->getBaseURL()."/user/processedit"); $this->view->assign('title','Member Editing'); $this->view->assign('label_fname','First Name'); $this->view->assign('label_lname','Last Name'); $this->view->assign('label_uname','User Name'); $this->view->assign('label_pass','Password'); $this->view->assign('label_submit','Edit'); $this->view->assign('description','Please update this form completely:'); } public function processAction() { $auth = Zend_Auth::getInstance(); if(!$auth->hasIdentity()){ $this->_redirect('/user/loginform'); }

$registry = Zend_Registry::getInstance(); $DB = $registry['DB'];

Page 49: Zend Framework Basic Tutorial P840

$request = $this->getRequest(); $data = array('first_name' => $request->getParam('first_name'), 'last_name' => $request->getParam('last_name'), 'user_name' => $request->getParam('user_name'), 'password' => md5($request->getParam('password')) ); $DB->insert('user', $data); $this->view->assign('title','Registration Process'); $this->view->assign('description','Registration succes'); } public function listAction() { $auth = Zend_Auth::getInstance(); if(!$auth->hasIdentity()){ $this->_redirect('/user/loginform'); }

$registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $sql = "SELECT * FROM `user` ORDER BY user_name ASC"; $result = $DB->fetchAssoc($sql); $this->view->assign('title','Member List'); $this->view->assign('description','Below, our members:'); $this->view->assign('datas',$result); } public function processeditAction() { $auth = Zend_Auth::getInstance(); if(!$auth->hasIdentity()){ $this->_redirect('/user/loginform'); }

$registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $request = $this->getRequest(); $data = array('first_name' => $request->getParam('first_name'), 'last_name' => $request->getParam('last_name'), 'user_name' => $request->getParam('user_name'), 'password' => md5($request->getParam('password')) ); $DB->update('user', $data,'id = '.$request->getParam('id'));

Page 50: Zend Framework Basic Tutorial P840

$this->view->assign('title','Editing Process'); $this->view->assign('description','Editing succes'); } public function delAction() { $auth = Zend_Auth::getInstance(); if(!$auth->hasIdentity()){ $this->_redirect('/user/loginform'); }

$registry = Zend_Registry::getInstance(); $DB = $registry['DB']; $request = $this->getRequest(); $DB->delete('user', 'id = '.$request->getParam('id')); $this->view->assign('title','Delete Data'); $this->view->assign('description','Deleting succes'); $this->view->assign('list',$request->getBaseURL()."/user/list"); } }?>

Learn Zend Framework Session

Introduction

Session is a familiar word in PHP programming. When we build complex application, usually, we involved session. In PHP, we know $_SESSION. It represent a logical, one to one connection between server-site, persistent state data, and user agent client (e.g, web browser). At Zend Framework, we can use Zend_Session. Zend_Session manage server-side data stored in $_SESSION. And a important class that we must know is Zend_Session_Namespace. Session namespaces provide access to session data using classic namespaces implemented logically as named groups of associative arrays, keyed by strings (similar to normal PHP arrays). Below, is quotes from zend framework manual:

Zend_Session_Namespace instances are accessor objects for namespaced slices of $_SESSION. The Zend_Session component wraps the existing PHP ext/session with an administration and management interface, as well as providing an API for Zend_Session_Namespace to persist session namespaces. Zend_Session_Namespace provides a standardized, object-oriented interface for working with namespaces persisted inside PHP's standard session mechanism. Support exists for both anonymous and authenticated (e.g., "login") session namespaces. Zend_Auth, the authentication component of the Zend Framework, uses Zend_Session_Namespace to store some information associated with authenticated users. Since Zend_Session uses the normal PHP ext/session functions internally, all the familiar configuration options and settings apply (see http://www.php.net/session), with such bonuses as the convenience of an object-oriented interface and default behavior that provides both best practices

Page 51: Zend Framework Basic Tutorial P840

and smooth integration with the Zend Framework. Thus, a standard PHP session identifier, whether conveyed by cookie or within URLs, maintains the association between a client and session state data.

Still confuse? Don't worry, next post we will try to practice about session at Zend Framework. We will begin with Zend_Session_namespace.

Using Namespace

In this post, we will learn to implement namespace into session at Zend Framework. If you are not familiar with namespace, don't worry. It is simple. Let's do it. Simply, namespace is like name of groups of associative arrays, keyed by strings. For practice, we use our previous practice.

Ok, we want to count number of a particular page request form a visitor. See this picture:

To do this, open your UserController.php within application/controllers. Include Zend/Session/Namespace.php at first line after delimeter.

require_once 'Zend/Session/Namespace.php';

Edit loginFormAction() method become like this:

public function loginFormAction() { $request = $this->getRequest();

$ns = new Zend_Session_Namespace('HelloWorld'); if(!isset($ns->yourLoginRequest)){ $ns->yourLoginRequest = 1;}else{ $ns->yourLoginRequest++;} $this->view->assign('request', $ns->yourLoginRequest);$this->view->assign('action', $request->getBaseURL()."/user/auth"); $this->view->assign('title', 'Login Form'); $this->view->assign('username', 'User Name');

Page 52: Zend Framework Basic Tutorial P840

$this->view->assign('password', 'Password'); }

At line 5, we define object of namespace. The namespace, we named "HelloWorld". It is like $_SESSION['HelloWorld']. You can put name such as mynamespace, myapplication, etc.

Next, at line 7, we check value of $ns->yourLoginRequest. It is like $_SESSION['HelloWorld']['yourLoginRequest']. Next, modify loginform.phtml within application/views/scripts/user. Update become like this:

<? include "header.phtml"; ?> <h1><?=$this->escape($this->title);?></h1> You have entered this page: <?=$this->escape($this->request);?> time(s). <form method='post' action='<?=$this->escape($this->action);?>'> <table> <tr> <td><?=$this->escape($this->username);?></td> <td><input type='text' name='username'></td> </tr> <tr> <td><?=$this->escape($this->password);?></td> <td><input type='password' name='password'></td> </tr> </table> <input type='submit' name='login' value='Login'> </form><? include "footer.phtml"; ?>

Now, point your browser to http://localhost/test/zend/helloworld/web_root/user/loginform. You may get screen like picture above.

Ok, try again for userPageAction() at controller. Update become like this:

public function loginFormAction() { $request = $this->getRequest();

$ns = new Zend_Session_Namespace('HelloWorld'); if(!isset($ns->yourLoginRequest)){ $ns->yourLoginRequest = 1;}else{ $ns->yourLoginRequest++;} $this->view->assign('request', $ns->yourLoginRequest);$this->view->assign('action', $request->getBaseURL()."/user/auth"); $this->view->assign('title', 'Login Form'); $this->view->assign('username', 'User Name'); $this->view->assign('password', 'Password'); }

Page 53: Zend Framework Basic Tutorial P840

Then, update its view at application/views/scripts/user/userpage.phtml:

<? include "header.phtml"; ?><h1>Hello, <?=$this->escape($this->real_name);?></h1>You have entered this page: <?=$this->escape($this->request);?> time(s).<a href='<?=$this->escape($this->urllogout);?>'>Logout</a><? include "footer.phtml"; ?>

Accessing Session Data

In this post, we learn how to access session data. Now, we talk about how to access the session. Please, give attention a code at previous post:

$ns = new Zend_Session_Namespace('HelloWorld'); if(!isset($ns->yourLoginRequest)){ $ns->yourLoginRequest = 1;}else{ $ns->yourLoginRequest++;}

From above, we know how to set session at Zend framework. Just give properties such as:$ns->yourLoginRequest = 1;$ns->thisIsSession = "Oke";$ns->nameOfSession = "MySession";$ns->foo = 10;

Now, how to access the values? Just simple:

echo $ns->yourLoginRequest;echo $ns->thisIsSession;echo $ns->nameOfSession;echo $ns->foo;

Seing All Values at Namespace

This is a little tips to show all value at a namespace. As we know, session can have behavior like array. So, we can show values like array. Look this sample: $ns = new Zend_Session_Namespace('HelloWorld');foreach ($ns as $index => $value) { echo "ns->$index = '$value';";}

Ok, try to test it. We have put session at loginform and userpage page. Now, we want to show request statistic for that page. Open your "UserController.php" within application/controllers. Add following method:

public function statsAction(){ $ns = new Zend_Session_Namespace('HelloWorld'); foreach ($ns as $index => $value) { echo "ns->$index = '$value';"; echo "<br />";

Page 54: Zend Framework Basic Tutorial P840

}

}

Then, create a view for this action controller. Create a file named "stats.phtml" within application/views/scripts/user. Leave blank.

Ok, try to point your browser to http://localhost/test/zend/helloworld/web_root/user/stats. You may get such as:

ns->yourLoginRequest = '2';ns->yourUserPageRequest = '7';

Values depend on number of visiting.

Locking and Unlocking Namespace

Session namespaces can be locked. What's that mean? When a namespace session is locked, we can not update or delete value of session. it will be read-only. We can use lock() to lock namespace. Then, if want to check whether locked or not, use isLocked(). Look this sample:

public function loginFormAction() {

$ns = new Zend_Session_Namespace('HelloWorld');$ns->lock();

if (!$ns->isLocked()) { if(!isset($ns->yourLoginRequest)){ $ns->yourLoginRequest = 1; }else{ $ns->yourLoginRequest++; } } $request = $this->getRequest(); $this->view->assign('request', $ns->yourLoginRequest);$this->view->assign('action', $request->getBaseURL()."/user/auth"); $this->view->assign('title', 'Login Form'); $this->view->assign('username', 'User Name'); $this->view->assign('password', 'Password');

}

To unlock, you can use unLock() method.

$ns= new Zend_Session_Namespace('HelloWorld');

// marking session as read only locked$ns->lock();

// unlocking read-only lockif ($ns->isLocked()) {

Page 55: Zend Framework Basic Tutorial P840

$ns->unLock();}

Automatic Expiration

We can set limited time for a namespace. For this feature, we called namespace expiration. Example, we want to count number of page request by a person in one minute. After 1 minute, he will be counted as new person. So, the code like this: We try at loginform. Open UserController.php within application/controllers. Update loginFormAction():

public function loginFormAction() {

$ns = new Zend_Session_Namespace('HelloWorld');

if(!isset($ns->yourLoginRequest)){ $ns->yourLoginRequest = 1;}else{ $ns->yourLoginRequest++;}

$ns->setExpirationSeconds(60); $request = $this->getRequest(); $this->view->assign('request', $ns->yourLoginRequest);$this->view->assign('action', $request->getBaseURL()."/user/auth"); $this->view->assign('title', 'Login Form'); $this->view->assign('username', 'User Name'); $this->view->assign('password', 'Password');

}

You can set only at a particular key (e.g, yourLoginRequest):$ns->setExpirationSeconds(60,'yourLoginRequest');