Archive | December, 2008

Zend_Acl (Access Control List) advance usage with example.

22 Dec

Since few days I am playing with Zend Framework Access control list(Zend_Acl).

The way Zend has implemented it is fabulous. You cannot even imagine how easy, efficient and flexible it is to implement roles in your application.

Zend_Acl doesn’t require any backend technology such as database, xml etc. You can store data were ever you like. Storing Acl data is totally left on developers.

If you truly like to see the power of Zend_Acl, see the following scenarios.

Suppose you want to develop an application for office, forget about web application for now, and you have employees who can access your contents only at the office timings e.g 9:00 to 5:00.

Or you have a web application for a specific country- user in that specified country can access your application. You want to block all other users from the globe.

Zend Framework acl provide very easy and convenient way of handling such type of situations.

Although this situation would be difficult to handle in simple php, however Zend Framework provides very simple and easy way to handle these situations.

To implement the first scenario, create My/Controller/Helper/TimeAssertion.php and add the following code.

One thing I would like to say is that please read my first article about Zend Acl before implementing what I have explained here.

<?php

Class My_Controller_Helper_TimeAssertion implements Zend_Acl_Assert_Interface

{

public function  assert(Zend_Acl $acl,Zend_Acl_Role_Interface $role=null, Zend_Acl_Resource_Interface $resource=null,$privilages=null)

{

return this->_isTime($date);

}

protected function _isTime($date)

{

$timeFrom = new Zend_Date();

$timeFrom->set(“09:00:00”,Zend_Date::TIME);

$timeTo = new Zend_Date();

$timeTo->set(“06:00:00”,Zend_Date::TIME);

if($date > $timeFrom && $dateTo < $timeTo){

return true;

} else {

return false;

}

}

}

?>

In the code above, we first define our class implementing Zend_Acl_Assert_Interface. This interface provides method “assert” function which is compulsory to be implemented when Zend_Acl_Assert_Interface is implemented.

In “asset” we simply call our protected method that return either true or false. The only parameter we are passing is the current date.

In our protected function _isTime, we first define two times. And then check if current date is between those two date. If condition is true, we return true, otherwise false.

Once you define your own class, the only change you will need to do is

$acl->allow(’employee’,null,’view’,new My_Controller_Helper_TimeAssertion());

That’s it, you don’t need to worry about the other things, because zend will do the magic for you.

Important: Read my first post on Zend_Acl.

CakePhp Installation and configuration

17 Dec

Installation of cake is very simple.

Download cake from cakephp.org and place it into your root directory. After placing it in the root directory. Simply write in your browser

http://localhost/cake/

you will be served with the default page, saying that “change config/database.php.default to config/database.php”. To do this open root_dir/cake/app/config/ and rename database.php.default to database.php.

keep in mind that the database.php.default is in the “app/” directory.

Now if you refresh the page you will see a message “Your database configuration file is present”. However you will see some warnings. To remove these warning you will need to make changes to your app/config/database.php file.

Open the file and make following changes.

var $default = array(

‘driver’ => ‘mysql’,

‘persistent’ => false,

‘host’ => ‘localhost’,

‘login’ => ‘root’,

‘password’ => ”,

‘database’ => ‘database_name’,

‘prefix’ => ”,

);

All the above information should match to your mysql configuration information, especially host, login, password, and database name.

Now after making these changes and saving the file. Refresh your url. You will see a message

“Cake is able to connect to the database”.

That’s it you have now installed and configured your cakephp successfully.

Grouping Form errors for display purpose in Zend Framework

5 Dec

Some time developers need to display summery of errors instead of displaying them with each form element. Previous version of Zend Framework was not providing way for grouping errors together, and display them above the form or any other place. However in ZF 1.7 this cool feature is added and now we can display summery of errors.

Recently I wrote a post on how to play with Zend Form error messages and straight away got a suggestion from Matthew Weier O’Phinney to use Zend_Form_Decorator_FormErrors available in the latest version. Thanks Matthew for giving such useful and easy solution.

In this post I am going to discuss this new cool feature with hope that it will help lot of souls.

Fist create your form as

<?

class forms_SimpleForm extends Zend_Dojo_Form

{

public function __construct($options = null)

{

parent::__construct($options);

$this->setMethod(‘post’);

$username=new Zend_Form_Element_Text(‘username’, array(

‘required’   => true,

‘label’      => ‘Username:’,

‘filters’    => array(‘StringTrim’, ‘StringToLower’),

‘validators’ => array(

‘Alnum’,

array(‘Regex’,false,array(‘/^[a-z][a-z0-9]{2,}$/’))

)

));

$username->removeDecorator(‘Errors’);

$password=new Zend_Form_Element_Password(‘password’, array(

‘required’   => true,

‘label’      => ‘Password:’,

‘filters’    => array(‘StringTrim’),

‘validators’ => array(

‘NotEmpty’,

array(‘StringLength’, false, array(6))

)

));

$password->removeDecorator(‘Errors’);

$save=new Zend_Form_Element_Submit(‘save’, array(

‘label’ => ‘save’,

‘required’=> false,

‘ignore’ => true,

));

$this->addElements(array($username, $password, $save));

$this->setDecorators(array(

‘FormElements’,

‘FormErrors’,

‘Form’

));

}

}

?>

In the above form you need to keep in mind the code

$username->removeDecorator(‘Errors’);

$password->removeDecorator(‘Errors’);

These two lines are compulsory. If you don’t include these two line, errors will be will render next to each line.

The final things, that you will need to include is

$this->setDecorators(array(

‘FormElements’,

‘FormErrors’,

‘Form’

));

If you remove “FormErrors”, error summery will not be render. The form render is

Zend Form errors summery

Zend Form errors summery

you can clearly see that instead of rendering error next to each elements. Errors are now rendered at the bottom. This is the default behavior of the Zend_From_Decorator_FormErrors. You can change this behavior by simply writing

$this->setDecorators(array(

‘FormElements’,

new Zend_Form_Decorator_FormErrors(array(

‘ignoreSubForms’=>true,

‘markupElementLabelEnd’=> ‘</b>’,

‘markupElementLabelStart’=> ‘<b>’,

‘markupListEnd’ => ‘</div>’,

‘markupListItemEnd’=>'</span>’,

‘markupListItemStart’=>'<span>’,

‘markupListStart’=>'<div’

)),

‘Form’

));

Instead of

$this->setDecorators(array(

‘FormElements’,

‘FormErrors’,

‘Form’

));

In your form.

The code above will wrap the whole errors summery in the “div” tag and individual element errors in “span” tag. The form render will be

Zend Form error summery in Div tag

Zend Form error summery in Div tag

Although the forms are looking identical, however they are not. If you see the source code you will see that the entire errors summery is now wrapped in the “div” tag.

By simply setting the style attribute of the “div” tag will place it where ever you want to display it.

Handling Zend Framework Form error messages

4 Dec

It’ll be very handy if you become able to play with Zend Form error messages. By default Zend Framework render errors messages in form of list next to each element.
Zend Form with error messages look like this.

Zend Form error messages rendered

Zend Form error messages rendered

We have a very easy way to remove these errors messages and place them wherever we like. However to do so you will need to make some changes in your form.
Just try the following form.
class forms_SimpleForm extends Zend_Dojo_Form
{
public function __construct($options = null)
{
parent::__construct($options);
$this->setMethod(‘post’);

$username=new Zend_Form_Element_Text(‘username’, array(
‘required’ => true,
‘label’ => ‘Username:’,
‘filters’ => array(‘StringTrim’, ‘StringToLower’),
‘validators’ => array(
‘Alnum’,
array(‘Regex’,
false,
array(‘/^[a-z][a-z0-9]{2,}$/’))
)
));

$username->removeDecorator(‘Errors’);

$password=new Zend_Form_Element_Password(‘password’, array(
‘required’ => true,
‘label’ => ‘Password:’,
‘filters’ => array(‘StringTrim’),
‘validators’ => array(
‘NotEmpty’,
array(‘StringLength’, false, array(6))
)
));

$password->removeDecorator(‘Errors’);

$save=new Zend_Form_Element_Submit(‘save’, array(
‘label’ => ‘save’,
‘required’=> false,
‘ignore’ => true,
));
$this->addElements(array($username, $password, $save));

}
}
?>
In the above code we have created three form elements named username, password and save. We have no concern with how we have created the Zend Form elements. In this post we are discussing error messages, so I am skipping the elements creating code.
The magic line for errors handling are
$username->removeDecorator(‘Errors’);
And
$password->removeDecorator(‘Errors’);

This two lines prevent error messages from displaying. Now if you submit the form you will find nothing next to the form elements. Form, after submission will now look like

Zend form without error messages

Zend form without error messages

We have now remove the error message from the place where they render by default. However we have not done yet. We will need to show these error message now in our view template. So place the following code into your view template where your are echoing your form.

<?php
$errorsMessages =$this->form->getMessages();
if(isset($errorsMessages[‘username’][‘isEmpty’])){
echo “Username is required field.”;
}
if(isset($errorsMessages[‘password’][‘isEmpty’])){
echo “Password is required field.”;
}
if(isset($errorsMessages[‘password’][‘stringLengthTooShort’])){
echo “Password must be more then 6 chars.”;
}

echo $this->form;
?>
The code in the “div” tag is important. In the first line we get the error messages array, check different condition and display appropriate error messages.

As you can see now you can play with these error messages and place them where ever you like. I got the following form after the submission.

Zend Form with error messages at the top

Zend Form with error messages at the top

Hope it will help you.

Creating Pdf files using Zend Framework Zend_Pdf component

3 Dec

Zend Framework provide component Zend_Pdf for creating pdf files. It is very easy to use this component.
Let’s have a look how to create pdf file using Zend_Pdf component.
First create instance of Zend_Pdf as

$pdf = new Zend_Pdf();


If you want to load existing pdf file and make changes, write this instead

$pdf = Zend_Pdf::load(‘path/to/file.pdf’);

If you want to save the file, simply write

$pdf->save(‘path/to/file.pdf’);


This will save new file. To update already existing file, write

$pdf->save(‘path/to/file.pdf’,’true’);

Or you can render your pdf file in the browser as

$pdf->render();

To add pages to the pdf file

$pdf->pages[] = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_LETTER);


Or

$pdf->pages[] = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);


To remove specific page from the document

unset($pdf->pages[$id]);

In order to write text to the page you will need the following code.

$page=$pdf->pages[0]; // this will get reference to the first page.

$style = new Zend_Pdf_Style();
$style->setLineColor(new Zend_Pdf_Color_Rgb(0,0,0));

$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES);

$style->setFont($font,12);

$page->setStyle($style);

$page->drawText(‘example text here’,100,($page->getHeight()-100));

In the code above we first get reference to the first page. In the next line we create instance of Zend_Pdf_Style and then setLineColor.
Next we set font by using Zend_Pdf_Font class.
Next two lines set the font to style and set style to page.
That’s it we have now set font and style.
Now its time to write text to the pdf file.
$page->drawText() does the magic for us.
That’s it. Have fun.

Caching data using Zend_Cache with example

1 Dec

Zend_Cache provide an easy and convenient way for caching data in order to increase speed. However it will not be a good idea to cache data that is constantly being changed or updated.
Zend Framework uses front end and backend to caching.
Front end is responsible for operating cache while backend uses different adapters to store cache records.
Records/Data once caches can be easily removed/deleted when needed.
In order to use Zend_Cache, you will need to make some necessary configuration in your bootstrap.
Write the following code into your bootstrap file.

$frontend= array(
‘lifetime’ => 7200,
‘automatic_seralization’ => true
);

$backend= array(
‘cache_dir’ => ‘./tmp/’,
);

$cache = Zend_Cache::factory(‘core’
‘File’,
$fontend,
$backend
);

Zend_Registry::set(‘cache’,$cache);

In the above code, we first define two array, $frontend and $backend, which contain cache configuration information. Several other configuration options are available and can be define in these array’s. see Zend Framework documentation for available options.

Next we define/get an instance of Zend_Cache by calling its factory method.
The arguments passed to factory method are important.
Fist parameter say that we want to use Zend_Cache_Core class. We are not going into the details of the Core classs this time. Hopefully we will explain it when we discuss advance topics.
The second parameter describe that we want to use file system for the storage of our cache data.
Third and forth are $fontend and $backend options array.
The last line is compulsory-Zend_Registry::set(‘cache’,$cache), for the future use.
That’s it we have now configured our application to use Zend_Cache component.
We can now cache whatever data we like.

In order to use cache object stored in the bootstrap. Write the following code in your controller or model.

$cache = Zend_Registry::get(‘cache’);
if(!$result = $cache->load(‘mydata’)) {
echo ‘caching the data…..’;
$data=array(‘1’,’2’,’3’);
$cache->save($data, ‘mydata’);
} else {

echo ‘retrieving cache data…….’
Zend_Debug::dump($result);
}

In the first line we get reference of the cached object that was stored in the bootstrap.
Next we check for already cache data. If data is not cached the we cached it using save() method of the Zend_Cache. Here we are simply cache array containing 1,2,3. However you can fetch records from the database and store it as we store simple array.
If the data has already been cached, we go to the else part and dump the stored array.
As we have configured our $frontend array to cache data for two hour, so the data cached will automatically be remove after two hours.
However if later in your application you want to clean the entire cached data manually, simply write

$cache->clean();

This will clean the entire cached data. However if you want to remove specific data being cached, write

$cache->remove(‘mydata’);

This will clean the data we cached in our example.