Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Thursday, November 8, 2012

Zend Framework 2 and ActiveRecord

I googled for adding php ActiveRecord in zend framework 2 but could not find it. However Arthur Bodera proposed the activerecord for zend framework 2 but it is not yet in Zend library. So i have decided to integrate standalone php ActiveRecord in zf2 as a third party library.

I have used zf2's tool to generated autoload classmap for activerecord that includes all ActiveRecord library files inside one file autoload_classmap.php. But activerecord has one file Utils.php, that include some functions outside class definition. The autoload classmap loader only find class methods not any function outside class, so i changed the Utils.php file and put all the outside functions into class and changed accordingly throughout the activerecord library. So if you wish to change the ActiveRecord library then please change Utils.php file accordingly.

You can find the complete code with zend framework 2 skeleton application here. Please put the zf2 library inside vendor directory. 

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.

Saturday, August 27, 2011

Facebook logout problem php solved

After two days of searching, i have found a problem solved link and i wanted to share it with you all. Put this line in your logout script before redirect to Facebook logout.

$session = $this->facebook->getSession();
$logoutUrl = $this->facebook->getLogoutUrl(array('next' => base_url(), 'session_key' => $session['session_key']));
setcookie('fbs_'.$this->facebook->getAppId(), '', time()-100, '/', '.domain.com');
$this->session->sess_destroy();
redirect($logoutUrl);

I got it from this link http://forum.developers.facebook.net/viewtopic.php?id=71219.

Hope it help 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.

Thursday, March 10, 2011

PHP Convert GMT time to local time

Get user timezone offset(ex. Timezone offset for nepal +5:45)
$userTzOffset = +5:45
$gmtDateTime = "2011-03-10 9:00"
$osts = explode(":",$userTzOffset);
$sec = ($osts[0] * 60 * 60) + $osts[1] * 60 ;
$gmtTimeStamp = strtotime($gmtDateTime, time()) + $sec;
$dt = date('Y-m-d::H:i:s',$gmtTimeStamp);

echo $dt;
Hope this will help someone.

Related post PHP Convert local time to GMT time

For getting timezone and offset see this post Get TimeZone with Daylight saving in PHP

PHP Convert local time to GMT time

Get user timezone offset(ex. Timezone offset for nepal +5:45)

$userTzOffset = +5:45
$userDateTime = "2011-03-10 14:00"

$osts = explode(":",$userTzOffset);
$secs = ($osts[0] * 60 * 60) + $osts[1] * 60 ;
$userTimeStamp = strtotime(date('Y-m-d H:i:s',time()+$secs));
$dt = date('Y-m-d H:i:s',strtotime($dateTime,$userTimeStamp) - $sec);
echo $dt;


Related Post PHP Convert GMT time to local time

For getting timezone and offset see this post Get TimeZone with Daylight saving in PHP

Wednesday, January 19, 2011

Get TimeZone with Daylight saving in PHP

function timeZones()
{
$list = DateTimeZone::listAbbreviations();
$idents = DateTimeZone::listIdentifiers();

$data = $offset = $added = array();
foreach ($list as $abbr => $info)
{
foreach ($info as $zone)
{
if ( ! empty($zone['timezone_id']) &&
! in_array($zone['timezone_id'], $added))
{
$z = new DateTimeZone($zone['timezone_id']);
$c = new DateTime('now', $z);
$value['offset'] = formatOffset($z->getOffset($c));

if($zone['dst'])
$day_light_saving = 'DST Yes';
else
$day_light_saving = 'DST No';

$value['timezone'] = $c->format('H:i a')." -- GMT ".$value['offset']." ".$zone['timezone_id']."--".$day_light_saving;
$data[$zone['timezone_id']] = $value;
$added[] = $zone['timezone_id'];
}
}

}

ksort($data);
return $data;

}

static private function formatOffset($offset)
{
$hours = $offset / 3600;
$remainder = $offset % 3600;
$sign = $hours > 0 ? '+' : '-';
$hour = (int) abs($hours);
$minutes = (int) abs($remainder / 60);

return $sign . str_pad($hour, 2, '0', STR_PAD_LEFT)
.':'. str_pad($minutes,2, '0');

}

Made simple correction from the below link discussions
http://stackoverflow.com/questions/1727077/generating-a-drop-down-list-of-timezones-with-php