How to get an unique identifier for php closure ?

June 17, 2013

Right to the example…

$identifier = spl_object_hash(function(){
  // some function content
});

Simple as that.

Suggestions or problems ? Write a comment.

How to read csv file into array ?

June 16, 2013
function csvToArray($file){
	$rows = array();
	$headers = array();
	if(file_exists($file) && is_readable($file)){
		$handle = fopen($file, 'r');
		while (!feof($handle) ) {
			$row = fgetcsv($handle, 10240);
			if(empty($headers))
				$headers = $row;
			else if(is_array($row))
				$rows[] = array_combine($headers, $row);
		}
		fclose($handle);
	} else {
		throw new Exception($file.' doesn`t exist or is not readable.');
	}
	return $rows;
}

Simple as that.

Suggestions or problems ? Write a comment.

How to use Zopim chat outside your site.

June 11, 2013

Most of the time Zopim chat makes your site slower.Here is an example how you can make your site load faster using Zopim chat.

Step 1.

Create html page zopim.html and put this code inside:




	
	
	

Step 2.

Go to the page where you want to put Zopim chat and put this code:


That is!

It is not so fancy , but definitely doing the job!

Simple as that.

Suggestions or problems ? Write a comment.

Zend Framework 2 Navigation with ACL in 3 steps

May 2, 2013

This post is a  follow up from : zend framework 2 acl in 5 minutes

Step 1

Code in config/autoload/global.php

'navigation' => array(
    'default'=> array(
      	array(
	    'label' => 'Home',
            'route' => 'home',
            'resource'=> 'home',
        ),
      	array(
	    'label' => 'Login',
            'route' => 'login',
            'resource'=> 'login',
        ),
      	array(
	    'label' => 'Register',
            'route' => 'register',
            'resource'=> 'register',
        ), 
    )
)

Step 2

Code in layout.phtml

echo $this->navigation('Navigation')->setAcl($this->acl)->setRole('guest');

Step 3

Add navigation factory in the config

Code in module.config.php

'service_manager' => array(
    'factories' => array(
       'Navigation' => 'Zend\Navigation\Service\DefaultNavigationFactory',
    ),
 ),

Simple as that.

Suggestions or problems ? Write a comment.

SEO Tip 1 Use WWW Domain

March 25, 2013

Use always www in front of your links.This way search engines will not consider http://yoursite.com different from http://www.yoursite.com
Use this code in .htacces (for domain root)

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Zend Framework 2 ACL setup in 5 minutes – tutorial

March 13, 2013

In this tutorial you will learn how to setup zend framework 2 acl and check if user has access for current route.

If you don`t have testing project , download one from here.

Add file module.acl.roles in application/config/

Tip: In fact role resources may be zend framework 2 routes.

return array(
	'guest'=> array(
		'home',
		'login',
		'register'
	),
	'admin'=> array(
		'admin',
		'add-user',
		'delete-user'
	),
);

Code in application/module.php

public function onBootstrap(MvcEvent $e) {
	$this -> initAcl($e);
	$e -> getApplication() -> getEventManager() -> attach('route', array($this, 'checkAcl'));
}

public function initAcl(MvcEvent $e) {

	$acl = new \Zend\Permissions\Acl\Acl();
	$roles = include __DIR__ . '/config/module.acl.roles.php';
	$allResources = array();
	foreach ($roles as $role => $resources) {

		$role = new \Zend\Permissions\Acl\Role\GenericRole($role);
		$acl -> addRole($role);

		$allResources = array_merge($resources, $allResources);

		//adding resources
		foreach ($resources as $resource) {
             // Edit 4
             if(!$acl ->hasResource($resource))
			    $acl -> addResource(new \Zend\Permissions\Acl\Resource\GenericResource($resource));
		}
		//adding restrictions
		foreach ($allResources as $resource) {
			$acl -> allow($role, $resource);
		}
	}
	//testing
	//var_dump($acl->isAllowed('admin','home'));
	//true

	//setting to view
	$e -> getViewModel() -> acl = $acl;

}

public function checkAcl(MvcEvent $e) {
	$route = $e -> getRouteMatch() -> getMatchedRouteName();
	//you set your role
	$userRole = 'guest';

	if (!$e -> getViewModel() -> acl -> isAllowed($userRole, $route)) {
		$response = $e -> getResponse();
		//location to page or what ever
		$response -> getHeaders() -> addHeaderLine('Location', $e -> getRequest() -> getBaseUrl() . '/404');
		$response -> setStatusCode(404);

	}
}

Edit 1

I am assuming that all the routes that are accessed in the app are already added to the acl config file.

If not replace :

if (!$e -> getViewModel() -> acl -> isAllowed($userRole, $route)) {

to

if ($e -> getViewModel() -> acl ->hasResource($route) && !$e -> getViewModel() -> acl -> isAllowed($userRole, $route)) {

 

Edit 2

If access inheritance is not needed just replace this :

//$allResources = array_merge($resources, $allResources);
foreach ($allResources as $resource) {
// with
foreach ($resources as $resource) {

 

Edit 3

But what about acl from the database someone will say ?

In the zend framework 2 startup tutorial they say – “Don`t go heavy in onBootstrap”

With that said , I think that an array file will work for most of the cases.

Add this method where acl check is

    public function getDbRoles(MvcEvent $e){
        // I take it that your adapter is already configured
        $dbAdapter = $e->getApplication()->getServiceManager()->get('Zend\Db\Adapter\Adapter');
        $results = $dbAdapter->query('SELECT * FROM acl');
        // making the roles array
        $roles = array();
        foreach($results as $result){
            $roles[$result['user_role']][] = $result['resource'];
        }
        return $roles;
    }

Then replace in initAcl

// this
$roles = include __DIR__ . '/config/module.acl.roles.php';
// with
$roles = $this->getDbRoles($e);

Simple as that.
Suggestions or problems ? Write a comment.

Zend Framework 2 hello world project

March 13, 2013

zend framework 2 logo

Download zend framework 2 hello word project.

How to convert european(eu) odds to united kingdom(uk) odds ?

March 12, 2013

A bit hard this one , but there is a way to convert EU odds to UK odds in php.

function eu_to_uk_odds($odds){
	if(floor($odds) !== $odds){
		$odds = (string) round($odds - 1,2);
		$oddsArr = explode('.',$odds);
		$f1 = (int) $oddsArr[0].''.$oddsArr[1]; 
		$f2 = str_pad('1', ($f1 >= 10 ? 3 : strlen($f1) ),'0',STR_PAD_RIGHT);
		$minDel = $this->gcd($f1,$f2);
		$odds = $f1 / $minDel .'/'.$f2/$minDel;	
	} else {
		$odds = ($odds-1).'/1';
	}	
	return $odds;	
}

function gcd($a, $b)
{
    if ($a == 0 || $b == 0)
        return abs( max(abs($a), abs($b)) );

    $r = $a % $b;
    return ($r != 0) ?
        $this->gcd($b, $r) :
        abs($b);
}

echo eu_to_uk_odds(2.3);
//13/100
echo eu_to_uk_odds(1.2);
//1/5

Simple as that.

How to count days between 2 dates in php

March 11, 2013

A simple solution to count days between 2 dates is using DateTime method since php 5.3

function getDaysBetweenDates($from,$to,$addLastDay = false){
	$d1 = new \DateTime($from);
	$d2 = new \DateTime($to);
	if($addLastDay){
		$d2->add(new \DateInterval('P1D'));
	}
	return $d1 -> diff($d2)->days;
}
echo getDaysBetweenDates('2013-03-01','2013-03-11');
//10
echo getDaysBetweenDates('2013-03-01','2013-03-11',true);
//11

If you need to count the last day too , just pass third parameter – true.

How to get zend framework 2 base path with domain name in layout ?

March 5, 2013

There is a easy way to get zend framework 2 base path with domain name in layout.

1. In layout.phtml

$homeUrl = $this->url('home',array(),array('force_canonical' => true));

2.Adding home route in module.config.php

'home' => array(
    'type'    => 'Zend\Mvc\Router\Http\Literal',
    'options' => array(
        'route' => '/',
        'defaults' => array(
            'controller' => 'Application\Controller\Index',
            'action'     => 'index',
        ),
    ),
),

Simple as that.

 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org