zend_toturial
TRANSCRIPT
Zend Framework Intro Zend Framework Step By Step Tutorial - Part 1: Zend 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:
Copy zend library (folder named "zend" under library) to helloworld/library. Thus, your application
become like this:
Next post, I will explain meaning of the folders.
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. Application 2. library 3. test 4. 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 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.
Next, we will write code for simple application named helloworld.
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:
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.
01 <?php
02 error_reporting(E_ALL|E_STRICT);
03 ini_set('display_errors', true);
04 date_default_timezone_set('Europe/London');
05
06 $rootDir = dirname(dirname(__FILE__));
07 set_include_path($rootDir . '/library' .PATH_SEPARATOR . get_include_path());
08
09 require_once 'Zend/Controller/Front.php';10 Zend_Controller_Front::run('../application/controllers');
11
12 ?>
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 to action controllers.
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:
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.
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:
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().
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
1 RewriteEngine On
2 RewriteRule .* index.php
01 <?php
02 require_once 'Zend/Controller/Action.php';03
04 class IndexController extendsZend_Controller_Action
05 {
06 public function indexAction()07 {
08 $this->view->assign('title', 'Hello, World!');
09 }
10
11 }
12 ?>
have a separate directory for each controllers view templates.
Create a file named "index.phtml" within views/scripts/index. Enter following code:
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.
Zend Framework Action 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:
01
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02 <html xmlns="http://www.w3.org/1999/xhtml">
03 <head>
04 <meta http-equiv="Content-Type"content="text/html; charset=utf-8" />
05 <title><? echo $this->escape($this->title); ?></title>
06 </head>
07
08 <body>
09 <h1><? echo $this->escape($this->title); ?></h1>
10 </body>
11 </html>
01 <?php
02 require_once 'Zend/Controller/Action.php';03
04 class IndexController extendsZend_Controller_Action
05 {
06 public function indexAction()07 {
08 $this->view->assign('title', 'Hello, World!');
09 }
View will catch with like this:
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:
Then, change you "index.phtml" within application/views/scripts/index.
10
11 }
12 ?>
1 <? echo $this->escape($this->title); ?>
01 <?php
02 require_once 'Zend/Controller/Action.php';03
04 class IndexController extendsZend_Controller_Action
05 {
06 public function indexAction()07 {
08 $this->view->assign('title', 'Hello, World!');
09$this->view->assign('wellcome','Wellcome
to my site. This site is built using Zend Framework. Enjoy it!');
10 $this->view->assign('webmaster','Wiwit');
11 }
12
13 }
14 ?>
01
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02 <html xmlns="http://www.w3.org/1999/xhtml">
03 <head>
04 <meta http-equiv="Content-Type"content="text/html; charset=utf-8" />
05 <title><? echo $this->escape($this->title); ?></title>
06 </head>
07
Point your browser to http://localhost/test/zend/helloworld/web_root/. May you get like this:
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 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:
08 <body>
09 <h1><? echo $this->escape($this->title); ?></h1>
10 <?=$this->escape($this->wellcome);?>
11 <p> </p>
12 <?=$this->escape($this->webmaster);?>
13 </body>
14 </html>
01 <?php
02 require_once 'Zend/Controller/Action.php';03
04 class UserController extendsZend_Controller_Action
05 {
06
Next, create a folder named "user" within helloworld\application\views\scripts. Create a file named "index.phtml" within user. Enter following code:
Now, point your browser to http://localhost/test/zend/helloworld/web_root/user.
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:
public function indexAction()07 {
08 $this->view->assign('name', 'Wiwit');
09 $this->view->assign('title', 'Hello');
10 }
11
12 }
13 ?>
01
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02 <html xmlns="http://www.w3.org/1999/xhtml">
03 <head>
04 <meta http-equiv="Content-Type"content="text/html; charset=utf-8" />
05 <title><? echo $this->escape($this->title); ?></title>
06 </head>
07
08 <body>
09 <h1><?=$this->escape($this->title);?>, <?=$this->escape($this->name);?></h1>
10 </body>
11 </html>
01 <?php
02 require_once 'Zend/Controller/Action.php';03
04 class UserController extendsZend_Controller_Action
05 {
06 public function indexAction()07 {
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:
Below, complete our userController:
Next, create a file named "name.phtml" within views/scrips/user. Enter following code:
08 $this->view->assign('name', 'Wiwit');
09 $this->view->assign('title', 'Hello');
10 }
11
12 }
13 ?>
1 public function nameAction()2 {
3 $this->view->assign('name', 'Wiwit');
4 $this->view->assign('title', 'User Name');
5 }
01 <?php
02 require_once 'Zend/Controller/Action.php';03
04 class UserController extendsZend_Controller_Action
05 {
06 public function indexAction()07 {
08 $this->view->assign('name', 'Wiwit');
09 $this->view->assign('title', 'Hello');
10 }
11
12 public function nameAction()13 {
14 $this->view->assign('name', 'Wiwit');
15 $this->view->assign('title', 'UserName');
16 }
17
18 }
19 ?>
Now, point your browser to http://localhost/test/zend/helloworld/web_root/user/name
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:
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:
How to catch the parameters? Ok, we can learn from sample. Open UserController.php within application/controller. Update became like this:
01
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02 <html xmlns="http://www.w3.org/1999/xhtml">
03 <head>
04 <meta http-equiv="Content-Type"content="text/html; charset=utf-8" />
05 <title><? echo $this->escape($this->title); ?></title>
06 </head>
07
08 <body>
09 <h1><?=$this->escape($this->title);?>, <?=$this->escape($this->name);?></h1>
10 </body>
11 </html>
1 http://hostname/user/name/username/wiwit/gender/man
1 http://hostname/controller/action/var1/value1/var2/value2/...
01 <?php
02 require_once 'Zend/Controller/Action.php';03
04 class UserController extendsZend_Controller_Action
05 {
Give attention at line 15-17. It is clear, isn't it?
Last, update your view: "name.phtml":
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.
06 public function indexAction()07 {
08 $this->view->assign('name', 'Wiwit');
09 $this->view->assign('title', 'Hello');
10 }
11
12 public function nameAction()13 {
14
15 $request = $this->getRequest();
16 $this->view->assign('name', $request->getParam('username'));
17 $this->view->assign('gender', $request->getParam('gender'));
18
19 $this->view->assign('title', 'User Name');
20 }
21 }
22 ?>
01
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02 <html xmlns="http://www.w3.org/1999/xhtml">
03 <head>
04 <meta http-equiv="Content-Type"content="text/html; charset=utf-8" />
05 <title><? echo $this->escape($this->title); ?></title>
06 </head>
07
08 <body>
09 <h1><?=$this->escape($this->title);?>, <?=$this->escape($this->name);?></h1>
10 <h2>Gender: <?=$this->escape($this->gender);?></h2>
11 </body>
12 </html>
Create a file named "header.phtml" within views/scripts/user. Enter following code:
Now, create a file named "footer.phtml" within views/scripts/user. Enter following code:
Last, update "name.phtml" within views/scripts/user with this:
Now, try to point your browser to http://localhost/test/zend/helloworld/web_root/user/name/username/wiwit/gender/man
Zend Framework Database 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.
If we talk about database in Zend Framework, we may talk what is Zend_Db_Adapter. This is basic
01
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02 <html xmlns="http://www.w3.org/1999/xhtml">
03 <head>
04 <meta http-equiv="Content-Type"content="text/html; charset=utf-8" />
05 <title><? echo $this->escape($this->title); ?></title>
06 </head>
07 <body>
08 <div id="header">
09 My Zend Framework
10 </div>
1 <div id="footer">
2 By PHPEveryday.com
3 </div>
4 </body>
5 </html>
1 <? include "header.phtml"; ?> 2 <h1><?=$this->escape($this->title);?>, <?=$this->escape($this->name);?></h1>
3 <h2>Gender: <?=$this->escape($this->gender);?></h2>
4 <? include "footer.phtml"; ?>
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 at here and here. 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:
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:
1 CREATE TABLE `user` (
2 `id` int(11) NOT NULL auto_increment,
3 `first_name` varchar(50) NOT NULL,
4 `last_name` varchar(50) NOT NULL,
5 `user_name` varchar(50) NOT NULL,
6 `password` varchar(255) NOT NULL,
7 PRIMARY KEY (`id`),
8 UNIQUE KEY `user_name` (`user_name`)
9 );
01 public function registerAction()02 {
03 $request = $this->getRequest();
04
05 $this->view->assign('action',"process");
06 $this->view->assign('title','MemberRegistration');
07 $this->view->assign('label_fname','First Name');
08 $this->view->assign('label_lname','Last Name');
09 $this->view->assign('label_uname','User Name');
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:
10 $this->view->assign('label_pass','Password');
11 $this->view->assign('label_submit','Register');
12 $this->view->assign('description','Please enter this form completely:');
13 }
01 <? include "header.phtml"; ?> 02 <h1><?=$this->escape($this->title);?></h1>
03 <div id="description">
04 <?=$this->escape($this->description);?>
05 </div>
06 <form name="register" method="post"action="<?=$this->escape($this->action)?>">
07 <table>
08 <tr>
09 <td><?=$this->escape($this->label_fname)?></td>
10 <td><input type="text"name="first_name"></td>
11 </tr>
12 <tr>
13 <td><?=$this->escape($this->label_lname)?></td>
14 <td><input type="text"name="last_name"></td>
15 </tr>
16 <tr>
17 <td><?=$this->escape($this->label_uname)?></td>
18 <td><input type="text"name="user_name"></td>
19 </tr>
20 <tr>
21 <td><?=$this->escape($this->label_pass)?
></td>
22 <td><input type="password"name="password"></td>
23 </tr>
24 </table>
25 <input type="submit" name="submit" value="<?=$this->escape($this->label_submit);?>">
26 </form>
Point your browser to http://localhost/test/zend/helloworld/web_root/user/register
Step Tutorial - Part 3: 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:
27 <? include "footer.phtml"; ?>
01 public function processAction()02 {
03
04 $params = array('host' =>'localhost',
05 'username' =>'root',
06 'password' =>'admin',
07 'dbname' =>'zend'
08 );
09 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);10
11 $request = $this->getRequest();
12 $sql = "INSERT INTO `user`
13 (`first_name` , `last_name` ,`user_name` ,`password`)
14 VALUES
15
('".$request->getParam('first_name')."', '".$request->getParam('last_name')."', '".$request->getParam('user_name')."', MD5('".$request->getParam('password')."'))";
16 $DB->query($sql);
17
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
. Enter following code:
18 $this->view->assign('title','Registration Process');
19 $this->view->assign('description','Registration succes');
20
21 }
Now, point your browser to http://localhost:8050/test/zend/helloworld/web_root/user/register.Then, enter a user information such as:
Click registration button. You will get like this:
1 <? include "header.phtml"; ?> 2 <h1><?=$this->escape($this->title);?></h1>
3 <h2><?=$this->escape($this->description);?></h2>
4 <a href="list">Member List</a>
5 <? include "footer.phtml"; ?>
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:
old query like this:
Ok, replace our processAction become like this:
1 $data = array('first_name' => $request->getParam('first_name'),
2 'last_name' => $request->getParam('last_name'),
3 'user_name' => $request->getParam('user_name'),
4 'password' => md5($request->getParam('password'))
5 );
6 $DB->insert('user', $data);
1 $sql = "INSERT INTO `user`
2 (`first_name` , `last_name` ,`user_name` ,`password`)
3 VALUES
4
('".$request->getParam('first_name')."', '".$request->getParam('last_name')."', '".$request->getParam('user_name')."', MD5('".$request->getParam('password')."'))";
5 $DB->query($sql);
01 public function processAction()02 {
03
04
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:
$params = array('host' =>'localhost',
05 'username' =>'root',
06 'password' =>'admin',
07 'dbname' =>'zend'
08 );
09 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);10
11 $request = $this->getRequest();
12 $data = array('first_name' => $request->getParam('first_name'),
13 'last_name' => $request->getParam('last_name'),
14 'user_name' => $request->getParam('user_name'),
15 'password' => md5($request->getParam('password'))
16 );
17 $DB->insert('user', $data);
18
19 $this->view->assign('title','Registration Process');
20 $this->view->assign('description','Registration succes');
21
22 }
01 public function listAction()02 {
03 $params = array('host' =>'localhost',
04 'username' =>'root',
05 'password' =>'admin',
06 'dbname' =>'zend'
07 );
08 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);09
10 $DB->setFetchMode(Zend_Db::FETCH_OBJ);
11
12$sql = "SELECT * FROM `user` ORDER BY
Then, create named "list.phtml" within application/views/scripts/user. Enter following code:
user_name ASC";
13 $result = $DB->fetchAssoc($sql);
14
15 $this->view->assign('title','Member List');
16 $this->view->assign('description','Below, our members:');
17 $this->view->assign('datas',$result);
18
19 }
01 <? include "header.phtml"; ?> 02 <h1><?=$this->escape($this->title);?></h1>
03 <h2><?=$this->escape($this->description);?></h2>
04 <a href="register">Register</a>
05 <table border="1">
06 <tr>
07 <th>ID</th>
08 <th>User Name</th>
09 <th>First Name</th>
10 <th>Last Name</th>
11 <th>Action</th>
12 </tr>
13 <? $datas = $this->datas;
14 for($i = 1; $i<= count($datas);$i++){ ?>
15 <tr>
16 <td><?=$datas[$i]['id']?></td>
17 <td><?=$datas[$i]['user_name']?></td>
18 <td><?=$datas[$i]['first_name']?></td>
19 <td><?=$datas[$i]['last_name']?></td>
20 <td>
21 <a href="edit/id/<?=$datas[$i]['id']?>">Edit</a>
22 |
23 <a href="del/id/<?=$datas[$i]['id']?>">Delete</a>
24 </td>
25 </tr>
26 <? } ?>
27 </table>
28
29 <? include "footer.phtml"; ?>
Point your browser to http://localhost/test/zend/helloworld/ web_root/user/list
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:
01 public function editAction()02 {
03 $params = array('host' =>'localhost',
04 'username' =>'root',
05 'password' =>'admin',
06 'dbname' =>'zend'
07 );
08 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);09
10 $request = $this->getRequest();
11 $id = $request->getParam("id");
12
13 $sql = "SELECT * FROM `user` WHERE id='".$id."'";
14 $result = $DB->fetchRow($sql);
15
16 $this->view->assign('data',$result);
17 $this->view->assign('action', $request->getBaseURL()."/user/processedit");
18 $this->view->assign('title','MemberEditing');
19 $this->view->assign('label_fname','First Name');
Then, create a file named "edit.phtml" within application/views/scripts/user. Enter following code:
20 $this->view->assign('label_lname','Last Name');
21 $this->view->assign('label_uname','User Name');
22 $this->view->assign('label_pass','Password');
23 $this->view->assign('label_submit','Edit');
24 $this->view->assign('description','Please update this form completely:');
25 }
01 <? include "header.phtml"; ?> 02 <h1><?=$this->escape($this->title);?></h1>
03 <div id="description">
04 <?=$this->escape($this->description);?>
05 </div>
06 <form name="edit" method="post" action="<?=$this->escape($this->action)?>">
07 <input type="hidden" name="id" value="<?=$this->data['id']?>">
08 <table>
09 <tr>
10 <td><?=$this->escape($this->label_fname)?></td>
11 <td><input type="text" name="first_name"value="<?=$this->data['first_name']?>"></td>
12 </tr>
13 <tr>
14 <td><?=$this->escape($this->label_lname)?></td>
15 <td><input type="text" name="last_name"value="<?=$this->data['last_name']?>"></td>
16 </tr>
17 <tr>
18 <td><?=$this->escape($this->label_uname)?></td>
19 <td><input type="text" name="user_name"value="<?=$this->data['user_name']?>"></td>
20 </tr>
21 </table>
22 <input type="submit" name="submit" value="<?=$this->escape($this->label_submit);?>">
23 </form>
24 <? 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:
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:
01 public function processeditAction()02 {
03 $params = array('host' =>'localhost',
04 'username' =>'root',
05 'password' =>'admin',
06 'dbname' =>'zend'
07 );
08 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);09 $request = $this->getRequest();
10
11 $sql = "UPDATE `user` SET `first_name` = '".$request->getParam('first_name')."',
12 `last_name` = '".$request->getParam('last_name')."',
13 `user_name` = '".$request->getParam('user_name')."'
14 WHERE id = '".$request->getParam('id')."'";
15 $DB->query($sql);
16
17 $this->view->assign('title','EditingProcess');
18 $this->view->assign('description','Editing succes');
19
Then, create a file named "processedit.phtml" within views/scripts/user. Enter following code:
Ok, try to update data from edit form.
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:
Following complete code for processeditAction method:
20 }
1 <? include "header.phtml"; ?> 2 <h1><?=$this->escape($this->title);?></h1>
3 <h2><?=$this->escape($this->description);?></h2>
4 <a href="list">Member List</a>
5 <? include "footer.phtml"; ?>
1 $data = array('first_name' => $request->getParam('first_name'),
2 'last_name' => $request->getParam('last_name'),
3 'user_name' => $request->getParam('user_name'),
4 'password' => md5($request->getParam('password'))
5 );
6 $DB->update('user', $data,'id = 1');
01 public function processeditAction()02 {
03 $params = array('host' =>'localhost',
04 'username' =>'root',
05 'password' =>'admin',
06 'dbname' =>'zend'
07 );
08 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);09 $request = $this->getRequest();
10
11 $data = array('first_name' => $request->getParam('first_name'),
12 'last_name' => $request->getParam('last_name'),
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.
Open your "UserController.php" within application/controllers. Add new method for delete action (i give name "delAction"):
Next, create a view for this action. Create a file named "del.phtml" within application/views/scripts/user. Enter following code:
13 'user_name' => $request->getParam('user_name'),
14 'password' => md5($request->getParam('password'))
15 );
16 $DB->update('user', $data,'id = '.$request->getParam('id'));
17
18 $this->view->assign('title','EditingProcess');
19 $this->view->assign('description','Editing succes');
20
21 }
01 public function delAction()02 {
03 $params = array('host' =>'localhost',
04 'username' =>'root',
05 'password' =>'admin',
06 'dbname' =>'zend'
07 );
08 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);09 $request = $this->getRequest();
10
11 $sql = "DELETE FROM `user` WHERE id='".$request->getParam('id')."'";
12 $DB->query($sql);
13
14 $this->view->assign('title','Delete Data');
15 $this->view->assign('description','Deleting succes');
16 $this->view->assign('list',$request->getBaseURL()."/user/list");
1 <? include "header.phtml"; ?>
Now, try to test from table data. Click link del at one of rows.
Zend Framework Database Step By Step Tutorial - Part 10: 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.
Ok, try to update your delAction become like this:
Oke, now, you are ready to read more about Zend Framework query style at Zend Framework manual guide.
Zend Framework Database Step By Step Tutorial - Part 11: This is last post from Zend Framework Database Tutorial series. In this post, you can look complete action that we had talked.
2 <h1><?=$this->escape($this->title);?></h1>
3 <h2><?=$this->escape($this->description);?></h2>
4 <a href="<?=$this->escape($this->list);?>">Member List</a>
5 <? include "footer.phtml"; ?>
1 $DB->delete('user', 'id = 3');
01 public function delAction()02 {
03 $params = array('host' =>'localhost',
04 'username' =>'root',
05 'password' =>'admin',
06 'dbname' =>'zend'
07 );
08 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);09 $request = $this->getRequest();
10
11 $DB->delete('user', 'id = '.$request->getParam('id'));
12
13 $this->view->assign('title','Delete Data');
14 $this->view->assign('description','Deleting succes');
15 $this->view->assign('list',$request->getBaseURL()."/user/list");
16
17 }
001 <?php
002 require_once 'Zend/Db/Adapter/Pdo/Mysql.php';003 require_once 'Zend/Controller/Action.php';004
005 class UserController extendsZend_Controller_Action
006 {
007 public function indexAction()008 {
009 $this->view->assign('name', 'Wiwit');
010 $this->view->assign('title', 'Hello');
011 }
012
013 public function nameAction()014 {
015
016 $request = $this->getRequest();
017 $this->view->assign('name', $request->getParam('username'));
018 $this->view->assign('gender', $request->getParam('gender'));
019
020 $this->view->assign('title', 'UserName');
021 }
022
023 public function registerAction()024 {
025 $request = $this->getRequest();
026
027 $this->view->assign('action',"process");
028 $this->view->assign('title','Member Registration');
029 $this->view->assign('label_fname','First Name');
030 $this->view->assign('label_lname','Last Name');
031 $this->view->assign('label_uname','User Name');
032 $this->view->assign('label_pass','Password');
033 $this->view->assign('label_submit','Register');
034 $this->view->assign('description','Pleaseenter this form completely:');
035 }
036
037 public function editAction()038 {
039 $params = array('host' =>'localhost',
040 'username' =>'root',
041 'password' =>'admin',
042 'dbname' =>'zend'
043 );
044 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);
045
046 $request = $this->getRequest();
047 $id = $request->getParam("id");
048
049 $sql = "SELECT * FROM `user` WHERE id='".$id."'";
050 $result = $DB->fetchRow($sql);
051
052 $this->view->assign('data',$result);
053 $this->view->assign('action', $request->getBaseURL()."/user/processedit");
054 $this->view->assign('title','Member Editing');
055 $this->view->assign('label_fname','First Name');
056 $this->view->assign('label_lname','Last Name');
057 $this->view->assign('label_uname','User Name');
058 $this->view->assign('label_pass','Password');
059 $this->view->assign('label_submit','Edit');
060 $this->view->assign('description','Pleaseupdate this form completely:');
061 }
062
063 public function processAction()064 {
065
066 $params = array('host' =>'localhost',
067 'username' =>'root',
068 'password' =>'admin',
069 'dbname' =>'zend'
070 );
071 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);
072
073 $request = $this->getRequest();
074 $data = array('first_name' => $request->getParam('first_name'),
075 'last_name' => $request->getParam('last_name'),
076 'user_name' => $request->getParam('user_name'),
077 'password' => md5($request->getParam('password'))
078 );
079 $DB->insert('user', $data);
080
081 $this->view->assign('title','Registration Process');
082 $this->view->assign('description','Registration succes');
083
084 }
085
086 public function listAction()087 {
088 $params = array('host' =>'localhost',
089 'username' =>'root',
090 'password' =>'admin',
091 'dbname' =>'zend'
092 );
093 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);
094
095 $DB->setFetchMode(Zend_Db::FETCH_OBJ);
096
097 $sql = "SELECT * FROM `user` ORDER BY user_name ASC";
098 $result = $DB->fetchAssoc($sql);
099
100 $this->view->assign('title','Member List');
101 $this->view->assign('description','Below,our members:');
102 $this->view->assign('datas',$result);
103
104 }
105
106 public function processeditAction()107 {
108 $params = array('host' =>'localhost',
109 'username' =>'root',
110 'password' =>'admin',
111 'dbname' =>'zend'
112 );
113 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);
114 $request = $this->getRequest();
115
116 $data = array('first_name' => $request->getParam('first_name'),
117 'last_name' => $request->getParam('last_name'),
118 'user_name' => $request->getParam('user_name'),
119 'password' => md5($request->getParam('password'))
120 );
121 $DB->update('user', $data,'id = '.$request->getParam('id'));
122
123 $this->view->assign('title','Editing Process');
124 $this->view->assign('description','Editing succes');
125
126 }
127
128 public function delAction()129 {
130 $params = array('host' =>'localhost',
131 'username' =>'root',
132 'password' =>'admin',
133 'dbname' =>'zend'
134 );
135 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);
136 $request = $this->getRequest();
137
138 $DB->delete('user', 'id = '.$request->getParam('id'));
139
140 $this->view->assign('title','Delete
Zend Framework Registry Step By Step Tutorial - Part 1: What is registry? It is like global storage. We just register values then we can use throughout 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:
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:
We set a parameter named "title". We put a value for this parameter.
Data');
141 $this->view->assign('description','Deleting succes');
142 $this->view->assign('list',$request->getBaseURL()."/user/list");
143
144 }
145
146 }
147 ?>
1 require_once 'Zend/Registry.php';
01 <?php
02 error_reporting(E_ALL|E_STRICT);
03 ini_set('display_errors', true);
04 date_default_timezone_set('Europe/London');
05
06 $rootDir = dirname(dirname(__FILE__));
07 set_include_path($rootDir . '/library' .PATH_SEPARATOR . get_include_path());
08
09
10 require_once 'Zend/Controller/Front.php';11 require_once 'Zend/Registry.php';12
13 Zend_Registry::set('title',"My First Application");
14
15
16 Zend_Controller_Front::run('../application/controllers');
17
18 ?>
2. Next, we try to call/read this registry. Open your UserController.php within application/controllers.
3. Update indexAction like this:
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.
Zend Framework Registry Step By Step Tutorial - Part 2: In this part we talk how to register array value and how to read them? Every value that we store at registry can we read as array. Ok, follow this steps to understand.
Open again your "index.php" within web_root. Update become like this:
1 public function indexAction()2 {
3 $title = Zend_Registry::get('title');
4 $this->view->assign('name', 'Wiwit');
5 $this->view->assign('title', $title);
6 }
01 <?php
02 error_reporting(E_ALL|E_STRICT);
03 ini_set('display_errors', true);
04 date_default_timezone_set('Europe/London');
05
06 $rootDir = dirname(dirname(__FILE__));
07 set_include_path($rootDir . '/library' .PATH_SEPARATOR . get_include_path());
08
09
10 require_once 'Zend/Controller/Front.php';11 require_once 'Zend/Registry.php';12
13 Zend_Registry::set('title',"My First Application");
14
15 $arrName = array('Ilmia Fatin','Aqila Farzana','Imanda Fahrizal');
16 Zend_Registry::set('credits',$arrName);
17
18
19 Zend_Controller_Front::run('../application/controllers');
20
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:
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:
Test by point your browser to http://localhost/test/zend/helloworld/web_root/user/.
21 ?>
01 public function indexAction()02 {
03 $registry = Zend_Registry::getInstance();
04
05 $title = $registry['title'];
06 $credits = $registry['credits'];
07 $strCredit = implode(", ",$credits);
08
09 $this->view->assign('name', 'Wiwit');
10 $this->view->assign('title', $title);
11 $this->view->assign('credits',$strCredit);
12 }
01
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02 <html xmlns="http://www.w3.org/1999/xhtml">
03 <head>
04 <meta http-equiv="Content-Type"content="text/html; charset=utf-8" />
05 <title><? echo $this->escape($this->title); ?></title>
06 </head>
07
08 <body>
09 <h1><?=$this->escape($this->title);?>, <?=$this->escape($this->name);?></h1>
10 credits: <?=$this->escape($this->credits);?>
11 </body>
12 </html>
Zend Framework Registry Step By Step Tutorial - Part 3: 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:
Then, read:
Ok, for practice, open index.php within web_root. Update become like this:
1 $params = array('host' =>'localhost',
2 'username' =>'root',
3 'password' =>'admin',
4 'dbname' =>'zend'
5 );
6 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);7
8 $DB->setFetchMode(Zend_Db::FETCH_OBJ);
9 Zend_Registry::set('DB',$DB);
1 $registry = Zend_Registry::getInstance();
2 $DB = $registry['DB'];
01 <?php
02 error_reporting(E_ALL|E_STRICT);
03 ini_set('display_errors', true);
04 date_default_timezone_set('Europe/London');
05
06 $rootDir = dirname(dirname(__FILE__));
07 set_include_path($rootDir . '/library' .PATH_SEPARATOR . get_include_path());
08
09
10 require_once 'Zend/Controller/Front.php';11 require_once 'Zend/Registry.php';12 require_once 'Zend/Db/Adapter/Pdo/Mysql.php';13
14 Zend_Registry::set('title',"My First Application");
15
16 $arrName = array('Ilmia Fatin','Aqila Farzana','Imanda Fahrizal');
Next, update "UserController.php" within application/controllers become like this:
17 Zend_Registry::set('credits',$arrName);
18
19 $params = array('host' =>'localhost',
20 'username' =>'root',
21 'password' =>'admin',
22 'dbname' =>'zend'
23 );
24 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);25
26 $DB->setFetchMode(Zend_Db::FETCH_OBJ);
27 Zend_Registry::set('DB',$DB);
28
29
30
31 Zend_Controller_Front::run('../application/controllers');
32
33 ?>
001 <?php
002
003 require_once 'Zend/Controller/Action.php';004
005 class UserController extendsZend_Controller_Action
006 {
007 public function indexAction()008 {
009 $registry = Zend_Registry::getInstance();
010
011 $title = $registry['title'];
012 $credits = $registry['credits'];
013 $strCredit = implode(", ",$credits);
014
015 $this->view->assign('name', 'Wiwit');
016 $this->view->assign('title', $title);
017 $this->view->assign('credits',$strCredit);
018 }
019
020 public function nameAction()021 {
022
023 $request = $this->getRequest();
024 $this->view->assign('name', $request->getParam('username'));
025 $this->view->assign('gender', $request->getParam('gender'));
026
027 $this->view->assign('title', 'UserName');
028 }
029
030 public function registerAction()031 {
032 $request = $this->getRequest();
033
034 $this->view->assign('action',"process");
035 $this->view->assign('title','Member Registration');
036 $this->view->assign('label_fname','First Name');
037 $this->view->assign('label_lname','Last Name');
038 $this->view->assign('label_uname','User Name');
039 $this->view->assign('label_pass','Password');
040 $this->view->assign('label_submit','Register');
041 $this->view->assign('description','Pleaseenter this form completely:');
042 }
043
044 public function editAction()045 {
046 $registry = Zend_Registry::getInstance();
047 $DB = $registry['DB'];
048
049 $request = $this->getRequest();
050 $id = $request->getParam("id");
051
052 $sql = "SELECT * FROM `user` WHERE id='".$id."'";
053 $result = $DB->fetchRow($sql);
054
055 $this->view->assign('data',$result);
056 $this->view->assign('action', $request->getBaseURL()."/user/processedit");
057 $this->view->assign('title','Member Editing');
058 $this->view->assign('label_fname','First Name');
059 $this->view->assign('label_lname','Last Name');
060 $this->view->assign('label_uname','User Name');
061 $this->view->assign('label_pass','Password');
062 $this->view->assign('label_submit','Edit');
063 $this->view->assign('description','Pleaseupdate this form completely:');
064 }
065
066 public function processAction()067 {
068
069 $registry = Zend_Registry::getInstance();
070 $DB = $registry['DB'];
071
072 $request = $this->getRequest();
073 $data = array('first_name' => $request->getParam('first_name'),
074 'last_name' => $request->getParam('last_name'),
075 'user_name' => $request->getParam('user_name'),
076 'password' => md5($request->getParam('password'))
077 );
078 $DB->insert('user', $data);
079
080 $this->view->assign('title','Registration Process');
081 $this->view->assign('description','Registration succes');
082
083 }
084
085 public function listAction()
086 {
087
088 $registry = Zend_Registry::getInstance();
089 $DB = $registry['DB'];
090
091 $sql = "SELECT * FROM `user` ORDER BY user_name ASC";
092 $result = $DB->fetchAssoc($sql);
093
094 $this->view->assign('title','Member List');
095 $this->view->assign('description','Below,our members:');
096 $this->view->assign('datas',$result);
097
098 }
099
100 public function processeditAction()101 {
102
103 $registry = Zend_Registry::getInstance();
104 $DB = $registry['DB'];
105
106 $request = $this->getRequest();
107
108 $data = array('first_name' => $request->getParam('first_name'),
109 'last_name' => $request->getParam('last_name'),
110 'user_name' => $request->getParam('user_name'),
111 'password' => md5($request->getParam('password'))
112 );
113 $DB->update('user', $data,'id = '.$request->getParam('id'));
114
115 $this->view->assign('title','Editing Process');
116 $this->view->assign('description','Editing succes');
117
118 }
Can you see it? It is simple, isn't it?
Zend Framework Config
Zend Framework Configuration Step By Step Tutorial - Part 1: 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. For case, see our code from previoustutorial:
119
120 public function delAction()121 {
122 $registry = Zend_Registry::getInstance();
123 $DB = $registry['DB'];
124
125 $request = $this->getRequest();
126
127 $DB->delete('user', 'id = '.$request->getParam('id'));
128
129 $this->view->assign('title','Delete Data');
130 $this->view->assign('description','Deleting succes');
131 $this->view->assign('list',$request->getBaseURL()."/user/list");
132
133 }
134
135 }
136 ?>
01 <?php
02 error_reporting(E_ALL|E_STRICT);
03 ini_set('display_errors', true);
04 date_default_timezone_set('Europe/London');
05
06 $rootDir = dirname(dirname(__FILE__));
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:
07 set_include_path($rootDir . '/library' .PATH_SEPARATOR . get_include_path());
08
09
10 require_once 'Zend/Controller/Front.php';11 require_once 'Zend/Registry.php';12 require_once 'Zend/Db/Adapter/Pdo/Mysql.php';13
14 Zend_Registry::set('title',"My First Application");
15
16 $arrName = array('Ilmia Fatin','Aqila Farzana','Imanda Fahrizal');
17 Zend_Registry::set('credits',$arrName);
18
19 $params = array('host' =>'localhost',
20 'username' =>'root',
21 'password' =>'admin',
22 'dbname' =>'zend'
23 );
24 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);25
26 $DB->setFetchMode(Zend_Db::FETCH_OBJ);
27 Zend_Registry::set('DB',$DB);
28
29
30
31 Zend_Controller_Front::run('../application/controllers');
32
33 ?>
01 <?php
02 error_reporting(E_ALL|E_STRICT);
03 ini_set('display_errors', true);
04 date_default_timezone_set('Europe/London');
05
06 $rootDir = dirname(dirname(__FILE__));
07 set_include_path($rootDir . '/library' .PATH_SEPARATOR . get_include_path());
08
09
10 require_once 'Zend/Controller/Front.php';11 require_once 'Zend/Registry.php';12 require_once 'Zend/Db/Adapter/Pdo/Mysql.php';13 require_once 'Zend/Config.php';14
15
16 $arrConfig = array(17 'webhost'=>'localhost',
18 'appName'=>'My First Zend',
19 'database'=>array(20 'dbhost'=>'localhost',
21 'dbname'=>'zend',
22 'dbuser'=>'root',
23 'dbpass'=>'admin'
24 )
25 );
26
27 $config = new Zend_Config($arrConfig);28
29 $title = $config->appName;
30 $params = array('host' =>$config->database->dbhost,
31 'username' =>$config->database->dbuser,
32 'password' =>$config->database->dbpass,
33 'dbname' =>$config->database->dbname
34 );
35
36
37 Zend_Registry::set('title',$title);
38
39 $arrName = array('Ilmia Fatin','Aqila Farzana','Imanda Fahrizal');
40 Zend_Registry::set('credits',$arrName);
41
42 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);43
44 $DB->setFetchMode(Zend_Db::FETCH_OBJ);
45 Zend_Registry::set('DB',$DB);
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.
Zend Framework Configuration Step By Step Tutorial - Part 2: 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:
To call this file, we can use like this:
This is complete code:
46
47
48
49 Zend_Controller_Front::run('../application/controllers');
50
51 ?>
01 <?
02 return array(03 'webhost'=>'localhost',
04 'appName'=>'My First Zend',
05 'database'=>array(06 'host'=>'localhost',
07 'dbname'=>'zend',
08 'username'=>'root',
09 'password'=>'admin'
10 )
11 );
12 ?>
1 $config = new Zend_Config(require'../application/config.php');
01 <?php
02 error_reporting(E_ALL|E_STRICT);
03 ini_set('display_errors', true);
04 date_default_timezone_set('Europe/London');
05
06 $rootDir = dirname(dirname(__FILE__));
07 set_include_path($rootDir . '/library' .PATH_SEPARATOR . get_include_path());
Zend Framework Configuration Step By Step Tutorial - Part 3: 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:
08
09
10 require_once 'Zend/Controller/Front.php';11 require_once 'Zend/Registry.php';12 require_once 'Zend/Db/Adapter/Pdo/Mysql.php';13 require_once 'Zend/Config.php';14
15 $config = new Zend_Config(require'../application/config.php');
16
17 $title = $config->appName;
18 $params = $config->database->toArray();
19
20 Zend_Registry::set('title',$title);
21
22 $arrName = array('Ilmia Fatin','Aqila Farzana','Imanda Fahrizal');
23 Zend_Registry::set('credits',$arrName);
24
25 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);26
27 $DB->setFetchMode(Zend_Db::FETCH_OBJ);
28 Zend_Registry::set('DB',$DB);
29
30
31
32 Zend_Controller_Front::run('../application/controllers');
33
34 ?>
1 ; Production site configuration data
2 [app]
3 webhost = www.example.com
4 title = My Zend Framework
5 database.host = localhost
6 database.username = root
7 database.password = admin
To read that config, we use like this:
Following complete code:
8 database.dbname = zend
1 require_once 'Zend/Config/Ini.php';2
3 $config = new Zend_Config_Ini('../application/config.ini','app');
4
5 $title = $config->appName;
6 $params = $config->database->toArray();
01 <?php
02 error_reporting(E_ALL|E_STRICT);
03 ini_set('display_errors', true);
04 date_default_timezone_set('Europe/London');
05
06 $rootDir = dirname(dirname(__FILE__));
07 set_include_path($rootDir . '/library' .PATH_SEPARATOR . get_include_path());
08
09
10 require_once 'Zend/Controller/Front.php';11 require_once 'Zend/Registry.php';12 require_once 'Zend/Db/Adapter/Pdo/Mysql.php';13
14 require_once 'Zend/Config/Ini.php';15
16 $config = new Zend_Config_Ini('../application/config.ini','app');
17
18 $title = $config->appName;
19 $params = $config->database->toArray();
20
21 Zend_Registry::set('title',$title);
22
23 $arrName = array('Ilmia Fatin','Aqila Farzana','Imanda Fahrizal');
24 Zend_Registry::set('credits',$arrName);
25
Zend Framework Configuration Step By Step Tutorial - Part 4: 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:
To access it, we can use:
Zend Framework LoginZend Framework Login System Step by Step Tutorial - Part 1: 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
26 $DB = new Zend_Db_Adapter_Pdo_Mysql($params);27
28 $DB->setFetchMode(Zend_Db::FETCH_OBJ);
29 Zend_Registry::set('DB',$DB);
30
31
32
33 Zend_Controller_Front::run('../application/controllers');
34
35 ?>
01 <?xml version="1.0"?>
02 <configdata>
03 <app>
04 <webhost>localhost</webhost>
05 <database>
06 <host>localhost</host>
07 <username>root</username>
08 <password>admin</password>
09 <dbname>zend</dbname>
10 </database>
11 </app>
12 </configdata>
1 require_once 'Zend/Config/Xml.php';2
3 $config = new Zend_Config_Xml('../application/config.xml','app');
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:
Now, try to insert sample member data for example:
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.
This is screenshot if we use phpMyAdmin.
Zend Framework Login System Step by Step Tutorial - Part 2: 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
1 CREATE TABLE `users` (
2 `id` int(11) NOT NULL auto_increment,
3 `username` varchar(50) NOT NULL,
4 `password` varchar(255) NOT NULL,
5 `real_name` varchar(50) NOT NULL,
6 PRIMARY KEY (`id`),
7 UNIQUE KEY `username` (`username`)
8 );
1 INSERT INTO `users`
2 (`id`, `username`, `password`, `real_name`)
3 VALUES
4(1, 'admin','21232f297a57a5a743894a0e4a801fc3','Administrator');
1 INSERT INTO `zend`.`users` (`id` ,`username` ,`password` ,`real_name`)
2 VALUES (NULL , 'admin', MD5( 'admin' ) , 'Administrator');
code:
Next, create loginformAction at controller. Open your UserController.php within application/controllers. Add following loginFormAction() method:
This 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:
01 <? include "header.phtml"; ?> 02 <h1><?=$this->escape($this->title);?></h1>
03 <form method='post' action='<?=$this->escape($this->action);?>'>
04 <table>
05 <tr>
06 <td><?=$this->escape($this->username);?></td>
07 <td><input type='text'name='username'></td>
08 </tr>
09 <tr>
10 <td><?=$this->escape($this->password);?></td>
11 <td><input type='password'name='password'></td>
12 </tr>
13 </table>
14 <input type='submit' name='login'value='Login'>
15 </form>
16 <? include "footer.phtml"; ?>
1 public function loginFormAction()2 {
3 $request = $this->getRequest();
4 $this->view->assign('action', $request->getBaseURL()."/user/auth");
5 $this->view->assign('title', 'Login Form');
6 $this->view->assign('username', 'User Name');
7 $this->view->assign('password','Password');
8
9 }
Zend Framework Login System Step by Step Tutorial - Part 3: 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():
Add authAction() like this:
1 <php
2 require_once 'Zend/Auth.php';3 require_once 'Zend/Auth/Adapter/DbTable.php';4
5 ...
6 >
01 public function authAction(){02 $request = $this->getRequest();
03 $registry = Zend_Registry::getInstance();
04 $auth = Zend_Auth::getInstance();
05
06 $DB = $registry['DB'];
07
08 $authAdapter = new Zend_Auth_Adapter_DbTable($DB);
09 $authAdapter->setTableName('users')
10 ->setIdentityColumn('username')
11 ->setCredentialColumn('password');
12
13 // Set the input credential values
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:
Next, we define table name, column that contains username and password.
Next, we catch HTTP parameter that contains username and password:
Next, do authentication:
14 $uname = $request->getParam('username');
15 $paswd = $request->getParam('password');
16 $authAdapter->setIdentity($uname);
17 $authAdapter->setCredential(md5($paswd));
18 // Perform the authentication query, saving the result
19 $result = $auth->authenticate($authAdapter);
20 if($result->isValid()){21 $data = $authAdapter->getResultRowObject
(null,'password');
22 $auth->getStorage()->write($data);
23 $this->_redirect('/user/userpage');
24 }else{25 $this->_redirect('/user/loginform');
26 }
27 }
1 $authAdapter = new Zend_Auth_Adapter_DbTable($DB);
1 $authAdapter->setTableName('users')
2 ->setIdentityColumn('username')
3 ->setCredentialColumn('password');
1 $uname = $request->getParam('username');
2 $paswd = $request->getParam('password');
3 $authAdapter->setIdentity($uname);
4 $authAdapter->setCredential(md5($paswd));
1 $result = $auth->authenticate($authAdapter);
2 if($result->isValid()){3 $data = $authAdapter->getResultRowObject(null,'password');
If valid user, we will save user data at session using:
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:
4 $auth->getStorage()->write($data);
5 $this->_redirect('/user/userpage');
6 }else{7 $this->_redirect('/user/loginform');
8 }
9 }
1 $data = $authAdapter->getResultRowObject(null,'password');
2 $auth->getStorage()->write($data);
001 <?php
002
003 require_once 'Zend/Controller/Action.php';004 require_once 'Zend/Auth.php';005 require_once 'Zend/Auth/Adapter/DbTable.php';006
007 class UserController extendsZend_Controller_Action
008 {
009
010
011 public function loginFormAction()012 {
013 $request = $this->getRequest();
014 $this->view->assign('action', $request->getBaseURL()."/user/auth");
015 $this->view->assign('title', 'Login Form');
016 $this->view->assign('username', 'User Name');
017 $this->view->assign('password','Password');
018
019 }
020
021 public function authAction(){022 $request = $this->getRequest();
023 $registry = Zend_Registry::getInstance();
024 $auth = Zend_Auth::getInstance();
025
026 $DB = $registry['DB'];
027
028 $authAdapter = newZend_Auth_Adapter_DbTable($DB);
029 $authAdapter->setTableName('users')
030 ->setIdentityColumn('username')
031 ->setCredentialColumn('password');
032
033 // Set the input credential values
034 $uname = $request->getParam('username');
035 $paswd = $request->getParam('password');
036 $authAdapter->setIdentity($uname);
037 $authAdapter->setCredential(md5($paswd));
038
039 // Perform the authentication query, saving the result
040 $result = $auth->authenticate($authAdapter);
041
042 if($result->isValid()){043 //print_r($result);
044 $data = $authAdapter->getResultRowObject(null,'password');
045 $auth->getStorage()->write($data);
046 $this->_redirect('/user');
047 }else{048 $this->_redirect('/user/loginform');
049 }
050
051 }
052
053
054 public function nameAction()055 {
056
057 $request = $this->getRequest();
058 $this->view->assign('name', $request->getParam('username'));
059 $this->view->assign('gender', $request->getParam('gender'));
060
061 $this->view->assign('title', 'UserName');
062 }
063
064 public function registerAction()065 {
066 $request = $this->getRequest();
067
068 $this->view->assign('action',"process");
069 $this->view->assign('title','Member Registration');
070 $this->view->assign('label_fname','First Name');
071 $this->view->assign('label_lname','Last Name');
072 $this->view->assign('label_uname','User Name');
073 $this->view->assign('label_pass','Password');
074 $this->view->assign('label_submit','Register');
075 $this->view->assign('description','Pleaseenter this form completely:');
076 }
077
078 public function editAction()079 {
080 $registry = Zend_Registry::getInstance();
081 $DB = $registry['DB'];
082
083 $request = $this->getRequest();
084 $id = $request->getParam("id");
085
086 $sql = "SELECT * FROM `user` WHERE id='".$id."'";
087 $result = $DB->fetchRow($sql);
088
089 $this->view->assign('data',$result);
090 $this->view->assign('action', $request->getBaseURL()."/user/processedit");
091 $this->view->assign('title','Member Editing');
092 $this->view->assign('label_fname','First Name');
093 $this->view->assign('label_lname','Last
Name');
094 $this->view->assign('label_uname','User Name');
095 $this->view->assign('label_pass','Password');
096 $this->view->assign('label_submit','Edit');
097 $this->view->assign('description','Pleaseupdate this form completely:');
098 }
099
100 public function processAction()101 {
102
103 $registry = Zend_Registry::getInstance();
104 $DB = $registry['DB'];
105
106 $request = $this->getRequest();
107 $data = array('first_name' => $request->getParam('first_name'),
108 'last_name' => $request->getParam('last_name'),
109 'user_name' => $request->getParam('user_name'),
110 'password' => md5($request->getParam('password'))
111 );
112 $DB->insert('user', $data);
113
114 $this->view->assign('title','Registration Process');
115 $this->view->assign('description','Registration succes');
116
117 }
118
119 public function listAction()120 {
121
122 $registry = Zend_Registry::getInstance();
123 $DB = $registry['DB'];
124
125 $sql = "SELECT * FROM `user` ORDER BY user_name ASC";
126 $result = $DB->fetchAssoc($sql);
127
128 $this->view->assign('title','Member List');
129 $this->view->assign('description','Below,our members:');
130 $this->view->assign('datas',$result);
131
132 }
133
134 public function processeditAction()135 {
136
137 $registry = Zend_Registry::getInstance();
138 $DB = $registry['DB'];
139
140 $request = $this->getRequest();
141
142 $data = array('first_name' => $request->getParam('first_name'),
143 'last_name' => $request->getParam('last_name'),
144 'user_name' => $request->getParam('user_name'),
145 'password' => md5($request->getParam('password'))
146 );
147 $DB->update('user', $data,'id = '.$request->getParam('id'));
148
149 $this->view->assign('title','Editing Process');
150 $this->view->assign('description','Editing succes');
151
152 }
153
154 public function delAction()155 {
156 $registry = Zend_Registry::getInstance();
157 $DB = $registry['DB'];
158
159 $request = $this->getRequest();
Zend Framework Login System Step by Step Tutorial - Part 4: 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:
Become:
Then, update line 346:
Become:
I will update this post if there is more better than this way. Do you want to share idea?
160
161 $DB->delete('user', 'id = '.$request->getParam('id'));
162
163 $this->view->assign('title','Delete Data');
164 $this->view->assign('description','Deleting succes');
165 $this->view->assign('list',$request->getBaseURL()."/user/list");
166
167 }
168
169 }
170 ?>
1 if ($resultIdentity['zend_auth_credential_match'] != '1') {
1 if ($resultIdentity->zend_auth_credential_match != '1') {
1 unset($resultIdentity['zend_auth_credential_match']);
1 unset($resultIdentity->zend_auth_credential_match);
Step by Step Tutorial - Part 5: 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.
Then, we add method at controller. Open "UserController.php". Add following method:
Zend Framework Login System Step by Step Tutorial - Part 6: 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).
1 <? include "header.phtml"; ?> 2 <h1>Hello, <?=$this->escape($this->username);?></h1>
3 <a href='<?=$this->escape($this->urllogout);?>'>Logout</a>
4 <? include "footer.phtml"; ?>
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.
01 public function userPageAction(){02 $auth = Zend_Auth::getInstance();
03
04 if(!$auth->hasIdentity()){05 $this->_redirect('/user/loginform');
06 }
07
08 $request = $this->getRequest();
09 $user = $auth->getIdentity();
10 $real_name = $user->real_name;
11 $username = $user->username;
12 $logoutUrl = $request->getBaseURL().'/user/logout';
13
14 $this->view->assign('username',$real_name);
15 $this->view->assign('urllogout',$logoutUrl);
16 }
Then, we create a method for controller named logoutAction(). Open "UserController.php" within application/controllers. Add following method:
We just use clearIdentity(). Then redirect page to another page (in this sample to user).
Zend Framework Login System Step by Step Tutorial - Part 7: 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():
Ok, below complete code for controller for this session:
1 public function logoutAction()2 {
3 $auth = Zend_Auth::getInstance();
4 $auth->clearIdentity();
5 $this->_redirect('/user');
6 }
01 public function indexAction()02 {
03 $request = $this->getRequest();
04 $auth = Zend_Auth::getInstance();
05 if(!$auth->hasIdentity()){06 $this->_redirect('/user/loginform');
07 }else{08 $this->_redirect('/user/userpage');
09 }
10 }
001 <?php
002
003 require_once 'Zend/Controller/Action.php';004 require_once 'Zend/Auth.php';005 require_once 'Zend/Auth/Adapter/DbTable.php';006
007 class UserController extendsZend_Controller_Action
008 {
009 public function indexAction()010 {
011 $request = $this->getRequest();
012 $auth = Zend_Auth::getInstance();
013 if(!$auth->hasIdentity()){014 $this->_redirect('/user/loginform');
015 }else{016 $this->_redirect('/user/userpage');
017 }
018 }
019
020 public function userPageAction(){021
022 $auth = Zend_Auth::getInstance();
023
024 if(!$auth->hasIdentity()){025 $this->_redirect('/user/loginform');
026 }
027
028
029 $request = $this->getRequest();
030 $user = $auth->getIdentity();
031 $real_name = $user->real_name;
032 $username = $user->username;
033 $logoutUrl = $request->getBaseURL().'/user/logout';
034
035 $this->view->assign('real_name',$real_name);
036 $this->view->assign('urllogout',$logoutUrl);
037 }
038
039 public function loginFormAction()040 {
041 $request = $this->getRequest();
042 $this->view->assign('action', $request->getBaseURL()."/user/auth");
043 $this->view->assign('title', 'Login Form');
044 $this->view->assign('username', 'User Name');
045 $this->view->assign('password','Password');
046
047 }
048
049 public function authAction(){
050 $request = $this->getRequest();
051 $registry = Zend_Registry::getInstance();
052 $auth = Zend_Auth::getInstance();
053
054 $DB = $registry['DB'];
055
056 $authAdapter = newZend_Auth_Adapter_DbTable($DB);
057 $authAdapter->setTableName('users')
058 ->setIdentityColumn('username')
059 ->setCredentialColumn('password');
060
061 // Set the input credential values
062 $uname = $request->getParam('username');
063 $paswd = $request->getParam('password');
064 $authAdapter->setIdentity($uname);
065 $authAdapter->setCredential(md5($paswd));
066
067 // Perform the authentication query, saving the result
068 $result = $auth->authenticate($authAdapter);
069
070 if($result->isValid()){071 //print_r($result);
072 $data = $authAdapter->getResultRowObject(null,'password');
073 $auth->getStorage()->write($data);
074 $this->_redirect('/user');
075 }else{076 $this->_redirect('/user/loginform');
077 }
078
079 }
080
081 public function logoutAction()082 {
083
084 $auth = Zend_Auth::getInstance();
085
086 if(!$auth->hasIdentity()){087 $this->_redirect('/user/loginform');
088 }
089
090 $auth->clearIdentity();
091 $this->_redirect('/user');
092 }
093
094 public function nameAction()095 {
096
097 $auth = Zend_Auth::getInstance();
098
099 if(!$auth->hasIdentity()){100 $this->_redirect('/user/loginform');
101 }
102
103
104 $request = $this->getRequest();
105 $this->view->assign('name', $request->getParam('username'));
106 $this->view->assign('gender', $request->getParam('gender'));
107
108 $this->view->assign('title', 'UserName');
109 }
110
111 public function registerAction()112 {
113 $auth = Zend_Auth::getInstance();
114
115 if(!$auth->hasIdentity()){116 $this->_redirect('/user/loginform');
117 }
118
119
120 $request = $this->getRequest();
121
122 $this->view->assign('action',"process");
123 $this->view->assign('title','Member Registration');
124 $this->view->assign('label_fname','First Name');
125 $this->view->assign('label_lname','Last Name');
$this->view->assign('label_uname','User
126 Name');
127 $this->view->assign('label_pass','Password');
128 $this->view->assign('label_submit','Register');
129 $this->view->assign('description','Pleaseenter this form completely:');
130 }
131
132 public function editAction()133 {
134 $auth = Zend_Auth::getInstance();
135
136 if(!$auth->hasIdentity()){137 $this->_redirect('/user/loginform');
138 }
139
140
141 $registry = Zend_Registry::getInstance();
142 $DB = $registry['DB'];
143
144 $request = $this->getRequest();
145 $id = $request->getParam("id");
146
147 $sql = "SELECT * FROM `user` WHERE id='".$id."'";
148 $result = $DB->fetchRow($sql);
149
150 $this->view->assign('data',$result);
151 $this->view->assign('action', $request->getBaseURL()."/user/processedit");
152 $this->view->assign('title','Member Editing');
153 $this->view->assign('label_fname','First Name');
154 $this->view->assign('label_lname','Last Name');
155 $this->view->assign('label_uname','User Name');
156 $this->view->assign('label_pass','Password');
157 $this->view->assign('label_submit','Edit');
158 $this->view->assign('description','Pleaseupdate this form completely:');
159 }
160
161 public function processAction()162 {
163 $auth = Zend_Auth::getInstance();
164
165 if(!$auth->hasIdentity()){166 $this->_redirect('/user/loginform');
167 }
168
169
170 $registry = Zend_Registry::getInstance();
171 $DB = $registry['DB'];
172
173 $request = $this->getRequest();
174 $data = array('first_name' => $request->getParam('first_name'),
175 'last_name' => $request->getParam('last_name'),
176 'user_name' => $request->getParam('user_name'),
177 'password' => md5($request->getParam('password'))
178 );
179 $DB->insert('user', $data);
180
181 $this->view->assign('title','Registration Process');
182 $this->view->assign('description','Registration succes');
183
184 }
185
186 public function listAction()187 {
188 $auth = Zend_Auth::getInstance();
189
190 if(!$auth->hasIdentity()){191 $this->_redirect('/user/loginform');
192 }
193
194
195 $registry = Zend_Registry::getInstance();
196 $DB = $registry['DB'];
197
198 $sql = "SELECT * FROM `user` ORDER BY user_name ASC";
199 $result = $DB->fetchAssoc($sql);
200
201 $this->view->assign('title','Member List');
202 $this->view->assign('description','Below,our members:');
203 $this->view->assign('datas',$result);
204
205 }
206
207 public function processeditAction()208 {
209 $auth = Zend_Auth::getInstance();
210
211 if(!$auth->hasIdentity()){212 $this->_redirect('/user/loginform');
213 }
214
215
216 $registry = Zend_Registry::getInstance();
217 $DB = $registry['DB'];
218
219 $request = $this->getRequest();
220
221 $data = array('first_name' => $request->getParam('first_name'),
222 'last_name' => $request->getParam('last_name'),
223 'user_name' => $request->getParam('user_name'),
224 'password' => md5($request->getParam('password'))
225 );
226 $DB->update('user', $data,'id = '.$request->getParam('id'));
227
228 $this->view->assign('title','Editing Process');
229 $this->view->assign('description','Editing succes');
Zend Framework Session Zend Framework Session Step By Step Tutorial - Part 1: 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:
230
231 }
232
233 public function delAction()234 {
235 $auth = Zend_Auth::getInstance();
236
237 if(!$auth->hasIdentity()){238 $this->_redirect('/user/loginform');
239 }
240
241
242 $registry = Zend_Registry::getInstance();
243 $DB = $registry['DB'];
244
245 $request = $this->getRequest();
246
247 $DB->delete('user', 'id = '.$request->getParam('id'));
248
249 $this->view->assign('title','Delete Data');
250 $this->view->assign('description','Deleting succes');
251 $this->view->assign('list',$request->getBaseURL()."/user/list");
252
253 }
254
255 }
256 ?>
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 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.
Zend Framework Session Step By Step Tutorial - Part 2: 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.
Edit loginFormAction() method become like this:
1 require_once 'Zend/Session/Namespace.php';
01 public function loginFormAction()02 {
03 $request = $this->getRequest();
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:
04
05 $ns = new Zend_Session_Namespace('HelloWorld');
06
07 if(!isset($ns->yourLoginRequest)){08 $ns->yourLoginRequest = 1;
09 }else{10 $ns->yourLoginRequest++;
11 }
12
13 $this->view->assign('request', $ns->yourLoginRequest);
14 $this->view->assign('action', $request->getBaseURL()."/user/auth");
15 $this->view->assign('title', 'Login Form');
16 $this->view->assign('username', 'User Name');
17 $this->view->assign('password','Password');
18
19 }
01 <? include "header.phtml"; ?> 02 <h1><?=$this->escape($this->title);?></h1>
03 You have entered this page: <?=$this->escape($this->request);?> time(s).
04 <form method='post' action='<?=$this->escape($this->action);?>'>
05 <table>
06 <tr>
07 <td><?=$this->escape($this->username);?></td>
08 <td><input type='text'name='username'></td>
09 </tr>
10 <tr>
11 <td><?=$this->escape($this->password);?></td>
12 <td><input type='password'name='password'></td>
13 </tr>
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:
Then, update its view at application/views/scripts/user/userpage.phtml:
14 </table>
15 <input type='submit' name='login'value='Login'>
16 </form>
17 <? include "footer.phtml"; ?>
01 public function loginFormAction()02 {
03 $request = $this->getRequest();
04
05 $ns = new Zend_Session_Namespace('HelloWorld');
06
07 if(!isset($ns->yourLoginRequest)){08 $ns->yourLoginRequest = 1;
09 }else{10 $ns->yourLoginRequest++;
11 }
12
13 $this->view->assign('request', $ns->yourLoginRequest);
14 $this->view->assign('action', $request->getBaseURL()."/user/auth");
15 $this->view->assign('title', 'Login Form');
16 $this->view->assign('username', 'User Name');
17 $this->view->assign('password','Password');
18
19 }
1 <? include "header.phtml"; ?> 2 <h1>Hello, <?=$this->escape($this->real_name);?></h1>
3 You have entered this page: <?=$this->escape
($this->request);?> time(s).
4 <a href='<?=$this->escape($this->urllogout);?>'>Logout</a>
5 <? include "footer.phtml"; ?>
Zend Framework Session Step By Step Tutorial - Part 3: 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:
From above, we know how to set session at Zend framework. Just give properties such as:
Now, how to access the values? Just simple:
Zend Framework Session Step By Step Tutorial - Part 4: 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:
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:
1 $ns = new Zend_Session_Namespace('HelloWorld');2
3 if(!isset($ns->yourLoginRequest)){4 $ns->yourLoginRequest = 1;
5 }else{6 $ns->yourLoginRequest++;
7 }
1 $ns->yourLoginRequest = 1;
2 $ns->thisIsSession = "Oke";
3 $ns->nameOfSession = "MySession";
4 $ns->foo = 10;
1 echo $ns->yourLoginRequest;
2 echo $ns->thisIsSession;
3 echo $ns->nameOfSession;
4 echo $ns->foo;
1 $ns = new Zend_Session_Namespace('HelloWorld');2 foreach ($ns as $index => $value) {
3 echo "ns->$index = '$value';";
4 }
1 public function statsAction()2 {
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:
Values depend on number of visiting.
Zend Framework Session Step By Step Tutorial - Part 5: 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:
3 $ns = new Zend_Session_Namespace('HelloWorld');
4 foreach ($ns as $index => $value) {
5 echo "ns->$index = '$value';";
6 echo "<br />";
7 }
8 }
1 ns->yourLoginRequest = '2';
2 ns->yourUserPageRequest = '7';
01 public function loginFormAction()02 {
03
04 $ns = new Zend_Session_Namespace('HelloWorld');
05 $ns->lock();
06 if (!$ns->isLocked()) { 07 if(!isset($ns->yourLoginRequest)){08 $ns->yourLoginRequest = 1;
09 }else{10 $ns->yourLoginRequest++;
11 }
12 }
13
14 $request = $this->getRequest();
15 $this->view->assign('request', $ns->yourLoginRequest);
16 $this->view->assign('action', $request-
To unlock, you can use unLock() method.
Zend Framework Session Step By Step Tutorial - Part 6: 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():
>getBaseURL()."/user/auth");
17 $this->view->assign('title', 'Login Form');
18 $this->view->assign('username', 'User Name');
19 $this->view->assign('password','Password');
20
21 }
1 $ns= new Zend_Session_Namespace('HelloWorld');2
3 // marking session as read only locked
4 $ns->lock();
5
6 // unlocking read-only lock
7 if ($ns->isLocked()) { 8 $ns->unLock();
9 }
01 public function loginFormAction()02 {
03
04 $ns = new Zend_Session_Namespace('HelloWorld');
05 if(!isset($ns->yourLoginRequest)){06 $ns->yourLoginRequest = 1;
07 }else{08 $ns->yourLoginRequest++;
09 }
10
11 $ns->setExpirationSeconds(60);
12
13 $request = $this->getRequest();
14 $this->view->assign('request', $ns->yourLoginRequest);
You can set only at a particular key (e.g, yourLoginRequest):
15 $this->view->assign('action', $request->getBaseURL()."/user/auth");
16 $this->view->assign('title', 'Login Form');
17 $this->view->assign('username', 'User Name');
18 $this->view->assign('password','Password');
19
20 }
1 $ns->setExpirationSeconds(60,'yourLoginRequest');