Showing posts with label zend framework. Show all posts
Showing posts with label zend framework. Show all posts

Thursday, January 19, 2012

Zend Flash message

For displaying flash message after certain event like, when user submit the page and need to show the success message in next request or in current request. For that Zend framework has a action helper FlashMessenger.

Here is a sample code that can used to flash the message.

Step 1: Add message to helper class in controller

$flash = $this->_helper->getHelper('FlashMessenger');
$flash->addMessage(array('success' => 'Posted message saved successfully' ));

Ste 2: Create View Helper to display message in layout

class Custom_View_Helper_FlashMessenger extends Zend_View_Helper_Abstract
{
public function flashMessenger ($width = null)
{
$flash = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');

#for message
$message = array();

if($flash->getCurrentMessages())
{
foreach($flash->getCurrentMessages() as $key => $msg)
{
$message[key($msg)][] = $msg[key($msg)];
}

$flash->clearCurrentMessages();
}
else if($flash->getMessages())
{
foreach($flash->getMessages() as $key => $msg)
{
$message[key($msg)][] = $msg[key($msg)];
}
}

$str_msg = null;
$style = '';

if($width) $style = "style='width:".$width."px'";

if(count($message) > 0)
{
foreach($message as $key => $arr_msg)
{
$key = ($key == 'error')?'errormsg':$key;

$str_msg .= '
';
$str_msg .= '

';

foreach($arr_msg as $msg)
{
$str_msg .= rtrim($msg,'.'). "
";
}
$str_msg .= '

';
$str_msg .= '
';
}
}

return $str_msg;
}

public function hasMessage()
{
$flash = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');

if($flash->hasMessages() || $flash->hasCurrentMessages())
return true;
else
return false;
}
}

Step 3: Display the message in layout




echo $this->flashMessenger();


Now you can add your falsh message in you any controller and it will display in you layout.

Hope this helps someone.

Thursday, July 7, 2011

Zend Custom breadcrumb using XML file

As we know a breadcrumb can be generated using Zend_Navigation easily. But this will apply only to navigation menu items, not for other extra actions (outside from menu). Here i have overwrite Zend Navigation breadcrumb view helper, so that a separate XML file can be used for breadcrumb.

To implement this there are 6 simple steps. I have used Custom_ as namespace either change it to any namespace that you have used in your application or add this namespace in you application.

Step 1 : Create Custom_BreadCrumb class by extending Zend_Navigation_Container


class Custom_BreadCrumb extends Zend_Navigation_Container
{
/**
* Creates a new bread container from zend navigation help
*
* @param array|Zend_Config $pages [optional] pages to add
* @throws Zend_Navigation_Exception if $pages is invalid
*/
public function __construct($pages = null)
{
if (is_array($pages) || $pages instanceof Zend_Config) {
$this->addPages($pages);
} elseif (null !== $pages) {
require_once 'Zend/Navigation/Exception.php';
throw new Zend_Navigation_Exception(
'Invalid argument: $pages must be an array, an ' .
'instance of Zend_Config, or null');
}
}
}

Step 2: Create an empty view helper class

class Custom_View_Helper_Breadcrumbs extends Zend_View_Helper_Navigation_Breadcrumbs{}

you can override some feature of breadcrumbs view helper inside this class.

Step 3: Create XML File name breadcrumb.xml inside application/config/breadcrumbs.xml










Step 4: Load breadcrumb in bootstrap

protected function _initViewHelpers() {
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
#breadcrumb
$breadCrubmConfig = new Zend_Config_Xml(APPLICATION_PATH . '/configs/breadcrumbs.xml');
$breadCrumb = new Custom_BreadCrumb($breadCrubmConfig);
$view->breadcrumbs($breadCrumb);
}


Step 5: Now set the breadcrumb active state in super action controller class

Note: Super action controller class means, all the controller class in an application should extend this class.

$module = $this->_request->getModuleName();
$controller = $this->_request->getControllerName();
$action = $this->_request->getActionName();
$mca = $module.'/'.$controller.'/'.$action;
$activeBreadCrumbs = $this->view->breadcrumbs()->findBymca($mca);
$activeBreadCrumbs->active = true;


Step 6: Usage

Just paste this line in your layout

echo $this->breadcrumbs()->setSeparator(' » ');

Happy coding...

Monday, April 4, 2011

Mongodb and Zend Framework using Mongo php library

Here you can use Mongodb(NoSql) database with Zend Framework using Mongo php library. I have created three classes Custom_Mongo_Instance, Custom_Mongo_Db and Custom_Mongo_Collection extending Mongo, MongoDB and MongoCollection respectively. So that you can overrides its methods easily.

First download mongo library for php from here

Step 1 : Custom_Mongo_Instanc

class Custom_Mongo_Instance extends Mongo
{
public function __construct( $server = "mongodb://localhost:27017", $options = array("connect" => TRUE) ) {
parent::__construct($server, $options);
}
}
Step 2 : Custom_Mongo_Db

class Custom_Mongo_Db extends MongoDB
{
public function __construct( Mongo $conn, $name ) {
parent::__construct( $conn, $name );
}
}
Step 3 : Custom_Mongo_Collection

class Custom_Mongo_Collection extends MongoCollection
{
public function __construct ( $name, $db = null ){
if($db == null) $db = Zend_Registry::get('mongoDB');
parent::__construct ( $db , $name );
}

public function insert( array $a, $options = array())
{
$a['created'] = date('Y-m-d H:i');
parent::insert( $a, $options);
}
}

Step 4 : Usage

$cnn = "mongodb://username:password@localhost:27017";
try{
$mongo = new Custom_Mongo_Instance($cnn);
$mongoDB = new Custom_Mongo_Db($mongo, "dbname");
}catch(Exception $e){echo $e->getMessage();exit;}

$collection = new Custom_Mongo_Collection("my_collection", $mongoDB);
$data['first_name'] = "Ritesh";
$data['last_name'] = "jha"
$collection->insert($data);

Thats all. Now you can check the data either using mongo console or some third party GUI admin tools.

Monday, March 28, 2011

RabbitMQ adapter for Zend Framework and Zend Queue using AMQP php library

You can use this class as Zend_Queue adapter for RabbitMQ queue system using AMQP php library.

Download AMQP extension from here

To compile and install follow this link

There are three steps

Note: Here i have used Custom_ namespace for Zend. You can change the namespace as per your choice.

Step 1 (Create Adapter class)

/**
* Class for using a Rabbitmq as a queue
*
* @category Custom
* @package Custom_Queue_Rabbitmq
* @subpackage Adapter
* @author Ritesh Jha
* @copyright Copyright (c) (http://mailrkj(at)gmail(dot)com)
*/

class Custom_Queue_Adapter_Rabbitmq extends Zend_Queue_Adapter_AdapterAbstract
{
/**
* @var object AMQP connection object
*/
protected $_cnn = array();

/**
*
* @var object AMQP excahnge object
*/
protected $_exchange = null;

/**
*
* @var object AMQP queue object
*/
protected $Queue = null;


/**
*
* @var object AMQP queue object
*/
protected $QueueFlag = AMQP_DURABLE;

/**
* Constructor
*
* @param array|Zend_Config $options
* options (host,port,login,password)
* @return AMQPConnection instance
*/
public function __construct($options, Zend_Queue $queue = null)
{
parent::__construct($options, $queue);

if(is_array($options))
{
try
{
$cnn = new AMQPConnection($options);
$cnn->connect();

if(!$cnn->isConnected())
{
throw new Zend_Queue_Exception("Unable to connect RabbitMQ server");
}
else
{
$this->_cnn = $cnn;
$this->Queue = new AMQPQueue($this->_cnn);
}
}catch(Exception $e){throw new Zend_Queue_Exception($e->getMessage());}
}
else
{
throw new Zend_Queue_Exception("The options must be an associative array of host,port,login, password ...");
}
}

/**
* Get AMQPConnection object
* @return object
*/
public function getConnection()
{
return $this->_cnn;
}


/**
* Set exchange for sending message to queue
* @param string $name
* @param string $type (AMQP_EX_TYPE_DIRECT, AMQP_EX_TYPE_FANOUT, AMQP_EX_TYPE_TOPIC or AMQP_EX_TYPE_HEADER)
* @param int $flags (AMQP_PASSIVE, AMQP_DURABLE, AMQP_AUTODELETE)
* @return boolean
*/
public function setExchange($exchange , $routingKey = "*", $type = AMQP_EX_TYPE_DIRECT, $flags = AMQP_DURABLE)
{
if($exchange instanceof Custom_Queue_Exchange)
{
$this->_exchange = $exchange;
}
else
{
$exchange = new Custom_Queue_Exchange($this->_cnn, $exchange , $type, $flags);
$this->_exchange = $exchange;
}
$this->setRoutingKey($routingKey);

return $exchange;
}

/**
* Set routing key for queu
* @param string $routing_key
* @param Custom_Queue $queue
* @return bool
*/
public function setRoutingKey($routingKey, Custom_Queue $queue = null)
{
if($queue)
$queueName = $queue->getName ();
else
$queueName = $this->_queue->getName();

return $this->_exchange->bind($queueName, $routingKey);
}

/**
* get AMQPQueue object
* @return
*/
public function setQueueFlag($flag)
{
return $this->QueueFlag = $flag;
}

/**
* create queue
* @param $name
* @param $timeout
*/
public function create($name, $timeout=null)
{
return $this->Queue->declare($name, $this->QueueFlag);
}

/**
* delete queue
* @param $name
* @param $timeout
*/
public function delete($name)
{
return $this->Queue->delete($name);
}

/**
* Publish message to queue
* @param mixed $message (array or string)
* @param Custom_Queue $queue
* @return boolean
*/
public function send($message, Zend_Queue $queue = null)
{
if(is_array($message))
{
$message = Zend_Json_Encoder::encode($message);
}

if($queue)
$routingKey = $queue->getOption('routingKey');
else
$routingKey = $this->_queue->getOption('routingKey');

if($this->_exchange)
{
return $this->_exchange->publish($message, $routingKey, AMQP_MANDATORY, array('delivery_mode' => 2));
}
else
{
throw new Zend_Queue_Exception("Rabbitmq exchange not found");
}
}

/**
*
* @param array $options (min, max. ack)
* @param int $timeout
* @param Zend_Queue $queue
* @return
*/
public function receive($options = null, $timeout = null, Zend_Queue $queue = null)
{
$messages = $this->Queue->get();
return $messages;
}

public function getCapabilities(){
return array(
'create' => true,
'delete' => true,
'send' => true,
);
}

public function isExists($name){}
public function getQueues(){}
public function count(Zend_Queue $queue = null){}
public function deleteMessage(Zend_Queue_Message $message){}
}


Step 2(Create Exchange Class)


class Custom_Queue_Exchange extends AMQPExchange
{
public function __construct ( AMQPConnection $connection , $exchange_name , $type = AMQP_EX_TYPE_DIRECT, $flags = AMQP_AUTODELETE)
{
parent::__construct ($connection);
$this->declare($exchange_name, $type, $flags);
}
}


Step 3(Overwrite Zend_Queue Class)

/**
* Class for using a Rabbitmq as a queue
*
* @category Custom
* @package Custom_Queue
* @subpackage Adapter
* @author Ritesh Jha
* @copyright Copyright (c) (http://mailrkj(at)gmail(dot)com)
*/

class Custom_Queue extends Zend_Queue
{
var $_instance = null;

public function __construct($adapter, $options = array())
{
if($adapter instanceof Custom_Queue_Adapter_Rabbitmq)
{
parent::__construct($adapter, $options);

#declare new queue
$queueName = (array_key_exists('name', $options))?$options['name']:'queue';
if(array_key_exists('flag', $options)) $adapter->setQueueFlag ($options['flag']);
$queue = $adapter->create($queueName);
$this->_setName($queueName);
#declare exchange
$routingKey = (array_key_exists('routingKey', $options))?$options['routingKey']:'*';
$exchangeName = (array_key_exists('exchange', $options))?$options['exchange']:'exchange';
$ex = $adapter->setExchange($exchangeName, $routingKey);
$this->setOptions($options);
}
else
{
throw new Zend_Queue_Exception("Invalid Rabbitmq adapter");
}
}

/**
* Create a new queue
* @param string $name queue name
* @param int $flag A bitmask of any of the flags: AMQP_AUTODELETE, AMQP_PASSIVE, AMQP_DURABLE, AMQP_NOACK.
* @return int (message count)
*/
public function createQueue($name, $flag = AMQP_DURABLE)
{
$this->getAdapter()->setQueueFlag($flag);
parent::createQueue($name);
}


/**
* Delete a queue and all of it's messages
* Returns false if the queue is not delete, true if the queue deleted
* @param string $name queue name
* @return boolean
*/
public function deleteQueue($name)
{
return $this->getAdapter()->delete($name);
}

/**
* Send a message to the queue
*
* @param array|string $message message
* @return Zend_Queue_Message
* @throws Zend_Queue_Exception
*/
public function send($message)
{
return $this->getAdapter()->send($message);
}

/**
* Consume message
*
* @param array $options
* @param int $timeout
* @return array
*/
public function receive($options = null, $timeout = null)
{
return $this->getAdapter()->receive($options, $timeout);
}
}
Usage:

Sending Message
try{
$adapter = new Custom_Queue_Adapter_Rabbitmq($adapteroptions);
$queue = new Custom_Queue($adapter, $queueoptions);
$message = 'Testing queue';
if($queue->send($message))
echo "Message published \n";
else
echo "Not";

} catch (Exception $e){echo $e->getMessage(); }

Receive Message

try{
$adapter = new Custom_Queue_Adapter_Rabbitmq($adapteroptions);
$queue = new Custom_Queue($adapter, $queueoptions);
$messages = $queue->receive($options);
} catch (Exception $e){echo $e->getMessage(); }