Archive | Zend Framework RSS feed for this section

Zend Framework: Sending Email with attachment in Zend Framework

5 Jul

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

Zend Framework and Dojo: configuration

1 Jul

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.

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.

17 Jun

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

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

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

31 May

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.

Zend Framework and JQuery: creating JQuery form in Zend

6 May

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

Zend Framework: Select statement and where clause examples

17 Apr

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.

Zend Framework: Uploading and renaming multiple files

16 Apr

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.