Posts tagged ‘zend framework’

Get date in Mysql format from Zend Date

25 October, 2010 | | 5 Comments

If you using ZF there is a high chance that you also using Zend Date when dealing with date and time.

One day you might need to get the date from a Zend Date object into Mysql format, but you will find out that none of the constants provides this. It’s a decision from developers to don’t mix database stuff with Zend Date.

Fortunately there is an easy way of doing this. If you have date fields on Mysql, you can use:

$date = new Zend_Date();

// Date field
echo $date->get('yyyy-MM-dd');

// Date time field
echo $date->get('yyyy-MM-dd HH:mm:ss');

But hold on, don’t start to write ‘yyyy-MM-dd’ everywhere on your application. If one day you change your database engine, or use a MySQL server with a different locale, you will need a good search and replace software to do it.

Instead of it, you can use a class with constants for the two field types. In this example i called the class Fm_Utils, but you can use the name that fits better on your application:

<?php
class Fm_Utils
{
    const DATABASE_DATE = 'yyyy-MM-dd';
    const DATABASE_DATETIME = 'yyyy-MM-dd HH:mm:ss';
}

Now you can simple use this to get date in Mysql format:

$date = new Zend_Date();

// Date field
echo $date->get(Fm_Utils::DATABASE_DATE);

// Date time field
echo $date->get(Fm_Utils::DATABASE_DATETIME);

And if one day you need to change your data platform, simply change the constant on this class.

How to identify the Zend Framework version?

22 September, 2010 | | No Comment

Quick tip today. If you need to identify the current Zend Framework version use:


echo Zend_Version::VERSION;

Which will result in something like this: 1.10.8.

Or open file Zend/Version.php and verify constant VERSION.

Understanding the Zend Framework bootstrap

19 September, 2010 | | 1 Comment

ZF Version: 1.10.8

The objetive of this article is to explain how Zend Framework bootstrap works and, at a second part, show samples of bootstrap for common components.

The bootstrap class is used to load common components or resources that are used by all or most of your controllers, views etc. On “non-framework” applications it is common to have something like includes/common.php to “bootstrap” your application.

At this place you usually:

  • Connect to database;
  • Start session;
  • Load config files;
  • Load common libraries;

On ZF bootstrap, the idea is almost the same. Let’s now, try with an example. Consider the following empty bootstrap:

<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

}

With ZF, all bootstrap methods starts with _init and are protected. Example:

<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
        protected function _initMonkeyAttack()
        {
                // Do your thing here
        }
}

This is just an example and you should always use things that describe what the method is doing. Unless you are really starting a monkey attack ( in this case, call me! ) change to something else.

Anything that starts with _init will be executed before application bootstrap.

What if i need to run method1 before method2?

It is common to require that one method is only called after another one. Example: the method that starts session should only start after the method that loads database, since your sessions are stored on database.

In this case, you can use $this->bootstrap( ‘nameOfTheMethod’ ); which will load a resource before the current one. Example:

<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
	protected function _initDb()
	{
		// Start database connection here
	}

	protected function _initSession()
	{
		// Bootstrap db first
		$this->bootstrap( 'db' );

		// Now start session
	}
}

That’s it. This is the first part of this article.  At the second part i will show bootstrap for common components like Zend_Db, Zend_Session, Zend_Translate, Zend_Locale etc.

Using Zend_Service_Twitter and Zend_OAuth

18 September, 2010 | | 3 Comments

ZF Version: 1.10.8

The source code of this post is available at GitHub.

At this short tutorial i will show to how use Zend_Service_Twitter and Zend_OAuth. I’m considering that:

  1. You have a working ZF environment.
  2. You have registered your application at Twitter.com and have the consumer key and secret.

I won’t get into the details of how OAuth work, since there are many tutorials about it. But to summarize what our controller will do:

  1. User access authenticate action and it’s redirected to Twitter.com
  2. If user allow application access, he gets back to our application on callback action.
  3. Callback action process the request and if user is authenticated, redirect to index action.
  4. Index action uses twitter service class to get user timeline ( or do other actions ).

The first thing is to define a few configuration parameters. Since they are common between your controller actions, we will place it at application.ini. So open file applications/configs/application.ini and add the following lines:

twitter.callbackUrl = "http://localhost/twitter/callback"
twitter.siteUrl = "http://twitter.com/oauth"
twitter.consumerKey = "yourConsumerKey"
twitter.consumerSecret = "yourConsumerSecret"

The directives are self explanatory, just make sure that the callback url is set to the correct action.

Now that you have the config, let’s create a controller for it. In this example, it will be called twitter:

<?php

class TwitterController extends Zend_Controller_Action
{
	public function init()
	{

	}

	public function indexAction()
	{

	}

	public function authenticateAction()
	{

	}

	public function callbackAction()
	{

	}
}

Since we will need the config variables on all actions, we define it at init method:

	public function init()
	{
		// Define zend config on registry. I'm doing it here, but you probably have this on your bootstrap
		$zendConfig = new Zend_Config_Ini( APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV );
		Zend_Registry::set( 'Zend_Config' , $zendConfig );
	}

We have to redirect user to Twitter.com, so that he can allow our application to access his account. This is done at authenticate action:

	public function authenticateAction()
	{
		$zendConfig = Zend_Registry::get( 'Zend_Config' );

		// Instance oauth consumer with config options
		$consumer = new Zend_Oauth_Consumer($zendConfig->twitter->toArray());

		// Using the default session namespace, we store the request token serialized
		$session = new Zend_Session_Namespace();
		$session->requestToken = serialize( $consumer->getRequestToken() );

		// Redirect user to twitter.com
		$consumer->redirect();
	}

If user clicks on allow, he will be redirected to the callback action with a series of GET parameters containing the auth info. We have to process it in order to get the access token.

	public function callbackAction()
	{
		$zendConfig = Zend_Registry::get( 'Zend_Config' );

		// Instance oauth consumer with config options
		$consumer = new Zend_Oauth_Consumer($zendConfig->twitter->toArray());

		// Use default session namespace
		$session = new Zend_Session_Namespace();

		// Check if we got a get request and that  user already have a request token
		if ( !empty( $this->_request->getQuery() ) && !empty( $session->requestToken ) ) {

			// Get access token
			$token = $consumer->getAccessToken( $this->_request->getQuery() , unserialize( $session->requestToken ) );

			// Store access token on a session variable. You can also store on DB, in case you want to use later
			$session->accessToken = serialize( $token );

			// Remove request token, not necessary anymore
			unset( $session->requestToken );

			// Redirect to index action
			return $this->_helper->redirector( 'index' );
		} else {
			throw new Exception( 'Invalid access. No token provided.' );
		}
	}

As you can see, if everything works user is redirected to index action. At index action, i’ve placed an example of how to get user recent tweets. Zend_Service_Twitter offers many functions, you can check them at ZF manual.

	public function indexAction()
	{
		// Default namespace
		$session = new Zend_Session_Namespace();

		try {
			// Check if user have access token.
			if ( empty( $session->accessToken ) ) {
				throw new Exception( 'You are not logged in. Please, try again.' );
			}

			// Unserialize access token
			$token = unserialize($session->accessToken);

			$zendConfig = Zend_Registry::get( 'Zend_Config' );

			// Prepare a config array with access token and config options
			$config = $zendConfig->twitter->toArray();
			$config['username'] = $token->getParam( 'screen_name' );
			$config['accessToken'] = $token;

			$twitter = new Zend_Service_Twitter( $config );

			// Verify if credentials work
			$response = $twitter->account->verifyCredentials();

			if ( !$response || !empty( $response->error ) ) {
				throw new Exception( 'Wrong credentials. Please, try to login again.' );
			}

			// Vardump user timeline ( one tweet )
			var_dump( $twitter->status->userTimeLine() );

		} catch ( Exception $e ) {

			echo $e->getMessage();
		}

		die();
	}

That’s it. Hope you found this tutorial userful.

If you want, you can download the full source-code: TwitterController.php.