Zend Framework

Archive for the ‘Zend Framework’ Category

Zend Framework: Sending Email with attachment in Zend Framework

Posted by Faheem Abbas on July 5, 2009

You may have used Php for sending emails in your application. I haven’t experienced it in plain php, so I don’t know whether its easy or difficult. I, however, know that Zend Framework provide very easy way for sending emails. You can even attach files with your email with single method call.
In this article I am going to discuss how to send email with attachments. Please do tell me whether it helped you or not. Read more here.http://zendgeek.blogspot.com/2009/07/sending-email-with-attachment-in-zend.html

Posted in Zend Framework | 1 Comment »

Zend Framework and Dojo: configuration

Posted by Faheem Abbas on July 1, 2009

Sorry this blog is deprecated. read full article here.

http://zendgeek.blogspot.com/2009/06/zend-framework-and-dojo-configuration.html

Latest version of Zend framework- ZF 1.6.0 ship dojo toolkit. You can find it in ZendFramework-1.6.0/external/ directory when you download ZF.

Recently I come across a problem using third party “calendar”- Java script Calendar, and as Zend has now done collaboration with Dojo, so people using zend will definitely start using Dojo for java scripts and all other functionality Dojo is providing. And that’s why I decided to study and use Dojo and implement it in my application instead of fixing the issue in the third party calendar.

Although Zend has done excellent job and has made things quite easy for those who wish to use dojo in their applications, however novice and those with little experience may find it a bit difficult to configure Zend for Dojo.

It this post I will tell you how to configure Zend for working with Dojo.

The first and most important thing is to copy “external/dojo” into your js directory under www/public folder.

Posted in Zend Framework | Leave a Comment »

Zend Framework: Zend_Loader::Zend_Loader::registerAutoload is deprecated as of 1.8.0 and will be removed with 2.0.0; use Zend_Loader_Autoloader instead.

Posted by Faheem Abbas on June 17, 2009

Sorry this blog is deprecated. you can read this article here.

http://zendgeek.blogspot.com/2009/06/zend-framework-zendloaderzendloaderregi.html

Posted in Zend Framework | 3 Comments »

Zend Framework and Facebook: writing a simple facebook application in Zend Framework

Posted by Faheem Abbas on May 31, 2009

In the social networking era, who don’t know about facebook. One of the famous and widely adopted social networking applications, where you can connect to your friends and family.

One the other hand Zend Framework is widely adopted open source MVC framework build in PHP.

Facebook has its own API classes for interacting with application. It also has language called FBML facebook markup language, FBJS facebook javascript for using javascript in facebook application, FQL, facebook query language for fetching data from database. Keep in mind that FBML is subset of HTML with some elements removed, and some added that are specific to facebook application.

Zend Framework on the other hand shipped with its own component like Zend_Auth for authentication, Zend_Acl for Access Control List, Zend_DB for connecting and working with database, Zend_Form for creating html forms and so on.

One of the nice things about Zend Framework is the configuration overhead and the use of component that are not tightly coupled.

To have a good understanding of both, I’d suggest you to read the documentation of both.

In this article I’m going to discuss how you can create a simple facebook application in Zend Framework.

Before Starting, download Zend Framework, create facebook application using faceboo.com/developers and download client library.

Once you successfully downloaded the facebook library. Next step is to create an appropriate directory structure.

I have the following directory structure.

Directory structure for creating facebook application in ZF

Directory structure for creating facebook application in ZF

well, don’t over think. The most important are application directory containing all our controllers, models and views.

The library directory contain two folders, facebook-platform that contain the facebook client library and Zend directory contain all the components shipped with Zend Framework.

The most important file here is index.php which serves as bootstrap file, getting all request from users and route them to specific controller/action.

 

The code you will need to include in this bootrap file(index.php), look like this.

<?php

require_once ‘facebook-platform/php/facebook.php’;

$appapikey = ‘dc42122221bc005c9d1153404a39a32667′;

$appsecret = ‘3e5c872ba5c7wew33204f2d153503f37′;

$appcallbackurl = ‘exmaple.com’;

$facebook = array(

                                    ‘appapikey’ => $appapikey,

                                    ‘appsecret’ => $appsecret,

                                    ‘appcallbackurl’ => $appcallbackurl

);

 

 

require_once “Zend/Loader.php”;

Zend_Loader::registerAutoload();

 

$registry = Zend_Registry::getInstance();

$registry->set(‘facebook’,$facebook);

 

$frontController = Zend_Controller_Front::getInstance();

$frontController->throwExceptions(true);

$frontController->setControllerDirectory(‘/application/controllers’);

$frontController->dispatch();

 ?>

This is the minimum code required.

The most important lines for facebook application are first few lines, where we are using require statement to include facebook.php file. Define a variable having own facebook application key, secret key and back url. We define an array and store all these information.

Once array of these facebook variable has been defined we get instance of Zend_Registry and set “facebook” to facebook array defined earlier for future use.

Next we get instance of front controller, set controller directory and call method dispatch.

That’s it. We have now properly defined our bootstrap file.

 

Next step is to create our first controller and define template files.

Go to application/controllers/ and create a file called IndexController.php and write the following code in it.

 

<?php

class IndexController extends Zend_Controller_Action

{

           

            public function indexAction()

            {

                        $face = Zend_Registry::get(‘facebook’);

                        $facebook = new Facebook($face['appapikey'], $face['appsecret']);

                        $user = $facebook->require_login();

                        try {

                        // If app is not added, then attempt to add

                        if (!$userId = $facebook->api_client->users_getLoggedInUser()) {

                                                $facebook->redirect($facebook->get_add_url());

                                    }

                        } catch (Exception $ex) {

                                    // code for handling exception

                        }

                        $friends = $facebook->api_client->friends_get();

                        $this->view->friends = $friends;

                        $this->view->user = $userId;

                       

            }

}

 

Here we have inherited our class from Zend_Controller_Action. And defined a single action named indexAction.

 

The first line

$face = Zend_Registry::get(‘facebook’);

return an array we earlier set in our bootstrap file. This array contain application key, secret key and call back url.

Next we create facebook application object, giving it application key and secret key.

Once we created the object, we call require_login() method. This will force user to logged in to facebook before moving forward.

Logging in is compulsory for fetching information from the facebook application.

Next we check if user has logged in by calling users_getLoggedInUser(). If not logged in we redirect user to the facebook log in page.

This user_getLoggedInUser() return ID of the current logged in user.

Next we get the friends of the user by using another useful method friends_get().

After getting this information, we assign it to our view as.

$this->view->friends = $friends;

$this->view->user = $userId;

That’s it. This is our simple controller/action.

Next step is to create our view and put the code we want.

For this, go to application/views/scripts/index/index.phtml. If this file has not been created, create one and put the following code in it

.

<?php

echo “<p><h4><fb:name uid=\”$this->user\” useyou=\”false\”/></h4></p>”;

echo “<p><h5>You have following friends</h5></p>”;

echo “<ul>”;

foreach ($this->friends as $friend) {

            echo “<li><fb:name uid=\”$friend\” useyou = \” fasle \” />”;

}

echo “</ul>”;

?>

To have a look what this is the output of this, browse

http://apps.facebook.com/orakzai/        

Any query and suggestion would be welcomed.

Posted in Zend Framework | 2 Comments »

Zend Framework and JQuery: creating JQuery form in Zend

Posted by Faheem Abbas on May 6, 2009

Sorry this blog is deprecated.

“Read new version of this article here.” http://zendgeek.blogspot.com/2009/07/creating-jquery-form-in-zend-framework.html

While few months back, I wrote an article on how to make Dojo Form in Zend Framework. Although dojo has numerous features, however most of the developers around prefer JQuery and prototype.

When Zend provide JQuery extension I wrote and article on how to use JQuery date picker.

While most of guys visited that article demand writing an article on how to create JQuery form in Zend Framework.

So  I’m here to show you how to use JQuery extension provide with latest version of Zend Framework for creating wonderful JQuery form.

You will need to follow the steps bellow to create JQuery form.

  1. Placing ZendX directory in right place
  2. Make necessary configuration in bootstrap file
  3. Write necessary code in your layout.phtml file.
  4. Create JQuery form
  5. and show that form in the template.

Placing ZendX directory in right place:

When you download latest version of Zend Framework and extract the zip file. You will see a directory called “extras”. When open that directory you will find ZendX folder. Copy this to your

Library/ folder at the same level of your Zend directory

You directory structure will be like this.

Library/

Zend/

ZendX/

Form show bellow will be displayed.

JQuery Form showing date picker

JQuery Form showing date picker

And the From will look like when first load

JQuery form when Date Selected

JQuery form when Date Selected

Posted in Zend Framework | 14 Comments »

Zend Framework: Select statement and where clause examples

Posted by Faheem Abbas on April 17, 2009

When it comes to retrieving data, nothing can be done unless using select statement. Sql is as easy as simple English, however we technical people don’t know much about languages and when think as functions, classes and objects. We love to use functions, modules, classes and objects. In sql

SELECT * FROM table_name

WHERE condition

Statement can easily be understood, however, how if we do the same things using functions and objects etc. It would be great, no doubt.

You’d be glad to work in Zend Framework if you think as I think. I feel comfortable using functions and objects. Another important thing is, you don’t need to learn sql if you don’t want, but only need to learn functions that do everything under the hood.

Zend Framework team has done a fabulous job, providing methods for interacting with database. Though all the database related things are impossible to cover in single post, I’d discuss the usage of select statement here.

I always encourage creation of separate php file for each of your database table in your models directory and create a custom class extending from Zend_Db_Table or Zend_Db_Table_Abstract.

The code can be written as

<?php

class Users extends Zend_Db_Table

{

protected $_name = ‘tbl_users’;

}

I assume that you have a table named “tbl_users”.

After extending your class from Zend_Db_Table, you get access to all the methods defined in Zend_Db_Table as well as Zend_Db_Table_Abstract, because Zend_Db_Table extends Zend_Db_Table_Abstract. The method available are in those two table are insert, update, delete etc.

Although you can use these methods provided by ZF in your controller by creating object of your own class. The code might be

$users = new Users();

$users->insert(array());

Keep in mind that here I have given an empty array, you can give associative array to insert specific values in specific columns of the tbl_users.

Although built-in function exist, however sometime you need to define your own custom methods.

Like

function getUserDataById($id) {

}

This function return data based on the id given. The code it may contain

Public function getUserDataById($id) {

$select = $this->_db->select()

->from($this->_name)

->where(‘id = ?’, $id);

$result = $this->getAdapter()->fetchAll($select);

return $result;

}

This is what I was intending to tell you. The from and where clauses. Its all seems simple. You don’t need to care how ZF build query for you.

The first line say, select and then from method is called, getting the name of the table. The where clause tells that id should be set to what we have sent as parameter.

Its very simple, isn’t it?

Wow, a question comes to mind how this query looks like in sql. Well, I want to say that ZF will create the following query for you.

SELECT * FROM tbl_users

WHERE id = 3

Yes if you have sent 3 as parameter. You can sent any number and the query will retrieve data based on that id.

Let’s make this query a bit complex, actually simple.

How if you want to select specific column only?

It will easy to do than say using ZF.

$select = $this->_db->select()

->from($this->_name,array(‘col2′,’col3′))

->where(‘id = ?’, $id);

I have made only one change, an additional array is sent as parameter to the from method.

Here col2 and col3 are the name of the column in the table tbl_users.

Another question can also come straight to mind.

How to And two condition? Like

WHERE id = 3 and name = ‘a’

It again very simple, write something like this.

$select = $this->_db->select()

->from($this->_name,array(‘col2′,’col3′))

->where(‘id = ?’, $id)

->where(‘name = ?’ , ‘a’);

Keep in mind that you can place “=” with any valid sql operator.

This will make an “AND” query.

What if you want to make “OR” query?

Its simple is that.

$select = $this->_db->select()

->from($this->_name,array(‘col2′,’col3′))

->where(‘id = ?’, $id)

->orwhere(‘name = ?’ , ‘a’);

I replaced where with orwhere, as simple as this.

Hopefully I’ll discuss some more magic of Zend_Db in coming days.

Cheers.

Posted in Zend Framework | 1 Comment »

Zend Framework: Uploading and renaming multiple files

Posted by Faheem Abbas on April 16, 2009

Waf!, I used Zend_File component about two month back. Did I test that before writing an article, yes surely, I did. But what, I did that for only one file, though I was intending to upload multiple files. I didn’t check my directory, however no exception was thrown and no error message jumped out. I thought that I have successfully completed my job and now its time to write an article to help those needed.

Sorry gays, I was completely wrong. The example, if you have used upload only one file.

A person once post his/her comments that It won’t upload multiple files, however I was having enough time to test my code again.

But today I decided that I will need to do something and make this example working as I was intending to make it. So I’m here to tell you how to upload multiple files.

An addition to uploading multiple files, I’d show you how to rename files.

In the first example I’d tell you how to upload multiple files and then in the second example I’d tell you how to rename them if you like.

So let have a look.

First of all, create your form as

<?php

class CustomForm extends Zend_Dojo_Form

{

public function init()

{

$this->setMethod(‘post’);

$this->setAttrib(‘enctype’, ‘multipart/form-data’);

$ this ->addElement(‘file’,'file1′,array(‘label’=>’File1′));

$ this ->addElement(‘file’,'file2′,array(‘label’=>’File1′));

$ this ->addElement(’submit’,’submit’);

}

}

In the code above we have done thing more than creating a form, setting its method, enctype, add two file elements and submit button.

Now in controller write

$form = new CustomForm();

$this->view->form = $form;

if($this->getRequest()->isPost()) {

if  ($form->isValid($_POST)) {

$adapter=new Zend_File_Transfer_Adapter_Http();

$uploadDir=dirname(__File__);

$adapter->setDestination($uploadDir);

foreach ($adapter->getFileInfo() as $info) {

if(!$adapter->receive($info['name'])){

$this->view->msg=$adapter->getMessages();

return;

}

}

}

}

Okay, the entire logic is written in the above code. First we create our own custom form instance and assign it to the view template. Then we check if the form is submitted by using isPost() method. In the next condition we check if the form is validly posted. I yes, we create an adapter. You will need to create transfer adapter.

In the next line we set our destination directory, directory we want to upload our files.

Foreach loop is compulsory for uploading multiple files, if you want to upload single file then there is no need to use this loop.

After the foreach loop we call receive method giving name of each file.

That’s it, we have done.

Renaming files will take some extra code. Make the following changes in your controller.

$form = new CustomForm();

$this->view->form = $form;

if($this->getRequest()->isPost()) {

if  ($form->isValid($_POST)) {

$adapter=new Zend_File_Transfer_Adapter_Http();

$uploadDir=dirname(__File__);

$adapter->setDestination($uploadDir);

$i= 1;

foreach ($adapter->getFileInfo() as $info) {

$ext = $this->_findexts($info['name']);

$fileName = ‘file’.$i.time().”.”.$ext;

$i++;

$adapter->addFilter(‘Rename’,

array(‘target’ => $uploadDir.DIRECTORY_SEPARATOR.$fileName,

‘overwrite’ => true));

if(!$adapter->receive($info['name'])){

$this->view->msg=$adapter->getMessages();

return;

}

}

}

}

protected function _findexts($filename)

{

$filename = strtolower($filename) ;

$exts = split(“[/\\.]“, $filename) ;

$n = count($exts)-1;

$exts = $exts[$n];

return $exts;

}

The only change made are in bold. We have defined a protected method for find the extension.

We call this function to get the file extension, which is concatenated with the name of the file, we are building.

The real part is performed by

$adapter->addFilter(‘Rename’,

array(‘target’ => $uploadDir.DIRECTORY_SEPARATOR.$fileName,

‘overwrite’ => true));

Here if don’t give “overwrite”, zend will generate error if file with the same name already exist.

Posted in Zend Framework | 5 Comments »

Zend Framework: using JSon and Prototype for filling form on fly

Posted by Faheem Abbas on April 2, 2009

I used JSon for the first time in my application today. Zend provide a very easy way to create JSon response.

In this article I would use Prototype to make ajax call. Hopefully you will know a bit about Prototype. Anyway if not, it’d not be a hard job to understand it after reading my article.

So let’s get started.

Consider you have the following form.

Zend Form

Zend Form

The scenario is

When user select name from the dropdown, the entire form is filled with the data from the database for that particular user.

For this purpose you would need to have a controller/Action(s), a model and template file.

In your form attach the following attrib to your name element as

$name = $this->createElement(’select’,'name’);

$name->addMultioptions(array(

’select’=>’[select]‘,

‘1′ => ‘Faheem’,

‘2′ => ‘Abbas’

));

$name->setAttrib(‘onchange’,'AutoFill(this.value)’);

In the lines above we first create a dropdown give it two values. And then attach javascript function “AutoFill” function using setAttrib method.

In your controller initialize your form and assign it to the view template as

$form = new MyCustomForm();

$this->view->form = $form;

Now in your view template file write the following.

Write the following javascript code.

<script>

function AutoFill(value)

{

new Ajax.Request(

“<?=$this->url(array(‘controller’=>’user’,'action’=>’getdata’))?>”,

{

method:’get’,

parameters: {id: value},

onSuccess: FillForm

}

);

}

function FillForm(rsp)

{

var card = eval(‘(‘ + rsp.responseText + ‘)’);

$(‘address1).value = card.items[0].address1;

$(‘address2′).value = card.items[0].address2;

$(‘postalcode’).value = card.items[0].postalcode;

}

</script>

To get response you will need to create an action and write the following code

<?php

class User extends Zend_Controller_Action

{

public function indexAction()

{

$form = new MyCustomForm();

$this->view->form = $form;

}

public function getdataAction()

{

$this->_helper->layout()->disableLayout();

$users = new Users();

$this->_helper->viewRenderer->setNoRender();

if ($this->getRequest()->isXmlHttpRequest()) {

$id = $this->_getParam(‘id’);

$userData = $ users ->getData($id);

$dojoData= new Zend_Dojo_Data(‘id’,$userData,’id’);

echo $dojoData->toJson();

}

}

}

In the above code getdataAction is called using ajax call. In the first line we have disabled the layout, because we don’t need layout in case of ajax response. Next we create object of our model class(discussed later). Next we tell zend to disable view rendering.

In the next few lines we check for ajax request, get id, call our getData model method.

We then create dojo data object. This object provide a very useful method to convert data retrieved into json format. The method used is toJson().

In our model we have code like the following.

<?php

class Users extends Zend_Db_Table

{

protected $_name = ‘users’;

public function getData($id)

{

$select = $this->_db->select()

->from($this->_name,

array(‘id’,'address1′,’address2′….))

->where(‘id = ?’, $id);

$result = $this->getAdapter()->fetchAll($select);

return $result;

}

}

Posted in Zend Framework | 11 Comments »

Zend Framework: working with layout and views (two step view)

Posted by Faheem Abbas on March 19, 2009

In this article I’m going to discuss layout and views and will give a practical example.

You may have heard of two step view.

The term two step view is used when we use layout and view templates for making our page look and feel.

Mostly you will need header, menu and footer same for the entire web application, only contents in the center of the page changes. So if this is the case you can get benefits out of two step views.

Create a layout containing header, menus and footer etc and view will have the contents relevant that specific page.

To implement two step view  in Zend framework you will need to make some configuration in bootstrap file.

Add the following lines to your bootstrap file.

$options = array(

    'layout'     => 'layout_name',

    'layoutPath' => '/path/to/layouts',

    

);
 
$layout = Zend_Layout::startMvc($options);

Keep in mind two things.
1.    Specify correct layout_name.
2.    Path to the layout file must be correct.
I usually prefer to create my layout directory in scripts directory under application/views.
 
If you create layout.phtml in your layouts directory you will need to define it as follows.
 

<?php
        include "header.phtml";
        
?>
// view contents goes here.
<?php
        
        <?=$this->layout()->content?>
 
?>
// footer goes here.
<?php
        include "footer.phtml"
?>

        
Now whatever request (controller/action) you made to your page, header and footer will be included in the response.

There may be cases (in some of your actions) where you don’t want your header and footer be appeared in the look and feel.

So write in those actions, the following line of code

$this->_helper->layout->disableLayout();

After including this line in your action, only the view contents will appear. It mean the contents in the header and footer will not be served.

Some time you need to execute only action code and redirect your request to another action instead of showing anything.

Write the following code in this case

$this->_helper->layout->disableLayout();

$this->_helper->viewRenderer->setNoRender();

Another very important thing is when you call a specific action, Zend Framework render a template file with the name similar to the action name. for example if you request view action, Zend will look for view.phtml file in the specific template directory.

If you want to render other then the default template, view.phtml in the above example. Write the following in your action.

$this->render(‘thanks’);

Posted in Zend Framework | 5 Comments »

Zend Framework: Using Zend Session and Session Namespace

Posted by Faheem Abbas on March 17, 2009

Session handling was one of the boring topic in plan php atleast for me, but in Zend Framework it really shines. If you like to work with Object oriented programming, you will definitely become fan of it.

In this article I’m going to discuss some useful techniques of using Zend Framework Session and Session namespace.

Keep in mind that Both Zend_Session and Zend_Session_Namespace extends abstract class Zend_Session_Abstract. So both inherit methods avaliable in Zend_Session_Abstract automatically.

If you want to go under the hood, you can open Zend/Session/Abstract.php and have a look at the functions available.

Instead of delve into the function available, I’d rather discuss some useful techniques.

“Read full article here”, http://zendgeek.blogspot.com/2009/07/zend-framework-session-usage-and.html

Posted in Zend Framework | 3 Comments »