php how to calculate system processor/s load in percent

February 7, 2013

This simple function will allow us to control php performance at level we need.

/**
 * Calculates the processor load in %
 * @see sys_getloadavg
 * @author Ivan Gospodinow
 * @site ivangospodinow.com
 * @date 07.02.2013
 * @param int $coreCount
 * @param int $interval
 * @return float
 */
function systemLoadInPercent($coreCount = 2,$interval = 1){
	$rs = sys_getloadavg();
	$interval = $interval >= 1 && 3 <= $interval ? $interval : 1;
	$load  = $rs[$interval];
	return round(($load * 100) / $coreCount,2);
}

Example:

echo systemLoadInPercent();
//42

current system load : 19.5%

and more

function to get system cores

/**
 * @see http://icesquare.com/wordpress/phphow-to-get-the-number-of-cpu-cores-in-fedora-ubuntu-and-freebsd/
 */
function getSystemCores(){
	$cmd = "uname";
	$OS = strtolower(trim(shell_exec($cmd)));

	switch($OS){
	   case('linux'):
	      $cmd = "cat /proc/cpuinfo | grep processor | wc -l";
	      break;
	   case('freebsd'):
	      $cmd = "sysctl -a | grep 'hw.ncpu' | cut -d ':' -f2";
	      break;
	   default:
	      unset($cmd);
	}

	if ($cmd != ''){
	   $cpuCoreNo = intval(trim(shell_exec($cmd)));
	}
	return empty($cpuCoreNo) ? 1 : $cpuCoreNo;
}

jQuery delayed events.

February 1, 2013

onDelay is simple jquery plugin that trigger events with delay.

/**
 * Trigger event delayed.
 * @author Ivan Gospodinow
 * @site http://www.ivangospodinow.com
 * @mail ivangospodinow@gmail.com
 * @date 01.02.2013
 */
(function($) {
    $.fn.onDelay = function(type, delay, funct) {
        delay = undefined === delay ? 500 : parseInt(delay);
        var timeOut;
        $(this).unbind(type)[type](function(e,x,y,z) {
            clearTimeout(timeOut);
            var self = this;
            timeOut = setTimeout(function(){
                funct.call(self,e,x,y,z);
            },delay);
        });
    };
})(jQuery);

How to use it ?

(function($) {
	$(window).onDelay('click', 2000, function(e) {
		console.log('Sorry , I am late.');
	})
})(jQuery);

UPDATED – Now supports $(this) in chield function.

UPDATED 25.11.2018

/**
 * Trigger event delayed.
 * @author Ivan Gospodinow
 * @site http://www.ivangospodinow.com
 * @mail ivangospodinow@gmail.com
 * @date 25.11.2018
 */
(function($) {
    $.fn.onDelay = function(events, selector, funct, delay) {
        var timeout;
        var callback = function (e) {
            clearTimeout(timeout);
            timeout = setTimeout(funct.bind(this, e), delay || 500);
        }
        $(this).off(events, selector, callback)
               .on(events, selector, callback);
    };
})(jQuery);

Suggestions or problems ?

Write a comment.

Comparing two objects in php

January 24, 2013
$areSame = (serialize($ob1) === serialize($ob2));

This easy way of comparing two objects in php.It will take in account object variables.
Example :

class ob1{
	public $number = 1;
}
class ob2{
	public $number = 1;
}

$areSame = serialize(new ob1()) === serialize(new ob2())
//$areSame = true;

class ob1{
	public $number = 1;
}
class ob2{
	public $number = 2;
}

$areSame = serialize(new ob1()) === serialize(new ob2())
//$areSame = false;

 

Suggestions or problems ?

Write a comment.

Change layout template based on controller in Zend Framework 2

January 18, 2013

In Zend Framework 2 , layout can be easily changed from module based on controller(name).

 

Step 1.

Add in module.config.php file

'controller_layouts' => array(
   'MyControllerName' =>  'layout/MyControllerName',
),

and

'view_manager' => array(
  //more options
 'template_map' => array(
    'layout/MyControllerName'=> PATH_TO_TEMPLATE
  ),
),

Step 2.

Add in module.php

$e->getApplication()->getEventManager()->getSharedManager()
  ->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
    $controller = $e->getTarget();
    $controllerClass = get_class($controller);
    $ar = explode('\\',$controllerClass);
	$controllerStr = str_replace('Controller','',$ar[count($ar) -1]);
    $config = $e->getApplication()->getServiceManager()->get('config');

    if (isset($config['controller_layouts'][$controllerStr])) {
        $controller->layout($config['controller_layouts'][$controllerStr]);
    }
}, 100);

 

Suggestions or problems ?

Write a comment.

How to destroy all dojo widget nodes

November 26, 2012

Simple and working solution.
This  code snippet will help you to destroy all dojo widgets.

	window.widgetsDestroy = function(){
		require(['dijit/registry','dojo/query'],function(registry,query){
			query('*[id]').forEach(function(node){
				var widget = registry.byId(node.id);
				if(undefined !== widget){
					widget.destroy();
				}
			});
		});
	}

Use it with :

window.widgetsDestroy();

Suggestions or problems ?

Write a comment.

Adding custom view helper (invocable) in Zend Framework 2

October 13, 2012

Simple as that:

    //File : App_folder/module/Module_name/config/module.config.php
    //some more configs
    'view_helpers' => array(
        'invokables' => array(
            'renderForm' => 'Some_Module\View\Helper\RenderForm',
        ),
    ), 
    //...

Suggestions or problems ?

Write a comment.

Simple Form Validator For Zend Framework 2 Forms

October 1, 2012

Here is some extended core , helping to auto validate Zend Framework 2 Form.

Step 1.

Extending Zend Framework 2 Form.

__addValidator();
		if ($request -> isPost()) {
			$query = $request -> getQuery();
			$query = is_object($query) ? $query->toArray() : $query;
			$post = $request -> getPost();
			foreach($post as $var=>$value){
				$query[$var] = $value;
			}
			$this -> setData($query);
			return parent::isValid();
		} else {
			return false;
		}
	}
	public function add($elementOrFieldset, array $flags = array()) {
		$form = parent::add($elementOrFieldset, $flags);
		$this->_rawElements[] = $elementOrFieldset;
		return $form;
	}
	private function __addValidator() {
		$this -> setInputFilter(new ExtendedFormValidator($this->_rawElements));
	}

}

Step 2.

Creating Zend Framework 2 Form Validator

//File : App_folder/module/Module_name/src/Module_name/Form/ExtendedFormValidator.php
namespace Application\Form;
use Zend\InputFilter\InputFilter;

class ExtendedFormValidator extends InputFilter {

	public function __construct($elements) {
		foreach ($elements as $element) {
			if (is_array($element)) {
				if (isset($element['type'])) {
					unset($element['type']);
				}
				$this -> add($element);
			}
		}
	}

}

Step 3.

Creating simple Zend Framework 2 Form and extending it with ExtendedForm

//File : App_folder/module/Module_name/src/Module_name/Form/ResendPassword.php
namespace Application\Form;

class ResendPassword extends ExtendedForm
{
    public function __construct($name = null)
    {

        parent::__construct('login');
        $this->setAttribute('method', 'post');

        $this->add(array(
        	'required'=>true,
            'name' => 'usermail',
            'type'  => 'Zend\Form\Element\Text',
            'options' => array(
                'label' => 'Email',
            ),
            'filters'=>array(
           		array('name'=>'StripTags'),
			    array('name'=>'StringTrim'),
			),
            'validators'=>array(
			    array('name'=>'EmailAddress')
			),

        ));

        $this->add(array(
            'name' => 'submit',
            'type' => 'Zend\Form\Element\Text',
            'attributes' => array(
                'type'  => 'submit',
                'value' => 'Submit',
                'id' => 'submitbutton',
            ),
        ));
    }
}

Step 4.

Instantiating the Zend Framework 2 Form.

//File : App_folder/module/Module_name/src/Module_name/Controller/IndexController.php
use Application\Form as Form; //at the top of the file.

public function forgotAction(){

	$form = new Form\ResendPassword();
	if($form->isValid($this->getRequest())){
          //do your magic
	}
	return new ViewModel(array('form'=>$form));	
}

Step 5.

Rendering Zend Framework 2 Form in the View.

//File : App_folder/module/Module_name/View/Module_name/index/index.phtml
$form =  $this->form;
$form->prepare();

echo $this->view->form()->openTag($form) . PHP_EOL;
$elements = $form->getElements();
foreach($elements as $element){
	echo $this->view->formRow($element) . PHP_EOL;
}
echo $this->view->form()->closeTag($form) . PHP_EOL;

 

Suggestions or problems ?

Write a comment.

Adding Custom View Helper In Zend Framework 2

September 30, 2012

Here is example implementation of a custom view helper script.

Step 1.

Creating Zend Framework 2 Helper.

//file : App_folder/module/Module_name/src/Module_name/View/Helper/SayHello.php

namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;

class SayHello extends AbstractHelper{

	public function __invoke($name = 'Unnamed'){
		return "$name , this is Zend Framework 2 View Helper";
	}
}

Step 2.

Registering the Zend Framework 2 Helper.

//file : App_folder/module/Module_name/Module.php

 public function getViewHelperConfig()
    {
        return array(
            'factories' => array(
                // the array key is the name of the invoke function that is called from view
                'sayHello' => function($name) {
                    return new SayHello($name);
                },
            ),
        );
    }

Step 3.

Using in Zend Framework 2 View.

//file : App_folder/module/Module_name/view/Module_name/index/index.phtml

 echo $this->sayHello('Ivan Gospodinow');

 

Suggestions or problems ?

Write a comment.

Running multiple wordpress blog copies from different locations.

September 30, 2012

This is something that was bugging me for a while. How can multiple developers work on same wordpress without messing up the code ?

The answer came from two wordpress variables : WP_SITEURL and WP_HOME.

If the two variables are set , wordpress blog do not get them from the database.

Step 1.

Adding this code at top of  wp-config.php

/**
 * This code adds base url for wordpress site.
 * This means that it will work no matter the directory , 
 * if get_parmalink() is used.
 * @author Ivan Gospodinow
 * @site http://www.ivangospodinow.com
 * @mail ivangospodinow@gmail.com
 * @date 30.09.2012
 */
foreach(array('/wp-admin','/wp-content','/wp-includes') as $_folder){
	if(strpos($_SERVER['PHP_SELF'],$_folder) !== false){
		$_r = explode($_folder,$_SERVER['PHP_SELF']);
		$_path = $_r[0];
		break;
	}
}
if(!isset($_path)){
	$_r = strrpos($_SERVER['PHP_SELF'], '/');
	$_path = substr($_SERVER['PHP_SELF'], 0,$_r);
}
$_http = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https':'http').'://';
/**
 * WP variables
 */
define('WP_SITEURL',$_http.$_SERVER['HTTP_HOST'].$_path);
define('WP_HOME', WP_SITEURL);

unset($_path,$_r,$_http,$_folder);

This code will insure that WP_SITEURL and WP_HOME variables point to current wordpress directory.

Step 2.

Adding non directory .htaccess

# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

# END WordPress

This code will insure that the .htaccess will work no matter the directory.

Step 3.

How to use this method ?

Install wordpress blog in folder ‘path_to_public_dir/dev/developer_1/project_name/’.

Do step 1 and step 2.

Copy project to folder ‘path_to_public_dir/dev/developer_2/project_name/’ or ‘path_to_public_dir/live/project_name/’.

 

Suggestions or problems ?

Write a comment.


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /home/c2kblate/sites/ivangospodinow.com/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org